2014-02-18 84 views
0

我有一個簡單陣列像這樣:設置與NG-重複的NG-模型值和複選框

$scope.otherItems = [ 
      "A", 
      "B", 
      "C", 
      "D", 
      "E" 
     ]; 

,我通過這個數組要循環和分配的值,以複選框像這樣:

<label ng-repeat="o in otherItems"> {{ o }} 
<input ng-model="myform.otherItems" type="checkbox" value="{{ o }}"> 
</label> 

現在我在這裏的問題是,當我檢查任何項目,他們都檢查!這是由於ng模型。我所有的複選框對ng-model都有相同的值。我想在提交/設置ng-model時收集各個複選框,如下所示:myform.otherItems.valueOfo,因此我得到所選複選框的一個對象。但是,當我嘗試設置ng-model像這樣ng-model="myform.otherItems.o"ng-model="myform.otherItems[o]"我收到錯誤。我如何最好地完成我想要的?提前謝謝了。

+0

是'myForm.otherItems'從'$ scope.otherItems'不同?或者它是相同的數組? –

+0

myForm.otherItems是我希望收集/提交的內容,因爲當我提交表單時,我傳遞包含其他項目(如文本框等)的myForm對象,$ scope.otherItems是通過複選框填充/循環的數組,並且isn'提交,這有道理嗎? –

回答

1

您想通過數組元素的索引來識別它。

ng-model="myform.otherItems[{{$index}}]" 

目前無法嘗試,但這可能會奏效。

0

如果您可以更改otherItems的格式或將值分配給新數組,則可以爲列表中的每個項目分配一個selected變量,並使用otherItems作爲模型。然後,您可以觀察模型上的更改並更新myform對象。

這裏的工作小提琴:http://jsfiddle.net/YQ2qJ/1/

查看:

<div ng-app=myApp> 
    <div ng-controller=myController> 
     <label ng-repeat="o in otherItems">{{ o.name }} 
      <input type="checkbox" ng-model="o.selected" value="{{ o.name }}"> 
     </label> 
     <p>{{myform}}</p> 
    </div> 
</div> 

控制器:

'use strict'; 

angular.module('myApp', []).controller('myController', ['$scope', function($scope) { 
    $scope.otherItems = [ 
     {name: "A", 
     selected: false 
     }, 
     {name: "B", 
     selected: false 
     }, 
     {name: "C", 
     selected: false 
     }, 
     {name: "D", 
     selected: false 
     }, 
     {name: "E", 
     selected: false 
     } 
    ]; 
    $scope.myform = {}; 
    $scope.$watch("otherItems", function() { 
     $scope.myform.otherItems = $scope.otherItems; 
    }); 
}]);