4

我想要使用AngularJS獲取複選框的所有選定對象。如何獲取AngularJS中複選框的所有選定對象?

下面是我的代碼

我view.tpl.html

<tr ng-repeat="item in itemList"> 
<td> 
<input type="checkbox" ng-click="clickedItem(item.id)" 
     ng-model="model.controller.object" 
     {{item.name}} /> 
</td> 

我的控制器

$scope.itemList = [ 
{ 
    id:"1", 
    name:"first item" 
}, 
{ 
    id:"2", 
    title:"second item" 
}, 
{ 
    id:"3", 
    title:"third item" 
} 
]; 

    $scope.selection = []; 
    $scope.clickedItem = function(itemId) { 
     var idx = $scope.selection.indexOf(itemId); 
     if (idx > -1) { 
      $scope.selection.splice(idx, 1); 
     } 

     // is newly selected 
     else { 
      var obj = selectedItem(itemId); 
      $scope.selection.push(obj); 
     } 
    }; 

    function selectedItem(itemId) { 
     for (var i = 0; i < $scope.itemList.length; i++) { 
      if ($scope.itemList[i].id === itemId) { 
       return $scope.itemList[i]; 
      } 
     } 
    } 

在這裏,我會得到所有的選擇伊特ms在$scope.selection。我怎樣才能得到ng-model

是否有可能做這樣ng-model="model.controller.object = selection",因爲我需要選擇$scope.selection如果我理解正確的話,你要創建一個複選框,並動態地將其從列表綁定到一個項目(S)被分配給model.controller.object

回答

7

,如果是這樣,這是我怎麼會去這樣做:

$scope.modelContainer=[]; 
angular.forEach($scope.itemList,function(item){ 
    $scope.modelContainer.push({item:item,checked:false }); 

}); 

HTML:

<div ng-repeat="item in itemList"> 
{{item.name}} 
<input type="checkbox" ng-click="selected(item.id)" ng-model="modelContainer[$index].checked"  /> 
</div> 

plunk。每當您選中複選框時,請查看控制檯中的模型容器更改。

+0

這不是我的情況。請再讀一遍我的問題。尤其是最後2行 – Prince

+0

我的確看過你的問題,但我告訴你退後一步,重新考慮你想做什麼,因爲你所要求的沒有意義:) –

+2

好的答案。如果你想讓每個複選框都有自己獨特的變量,那麼你實際上需要製作每個變量。在這個答案中描述的方法是儘可能乾淨的方式來做到這一點,因爲它可以得到。 – Hylianpuffball

相關問題