如何在AngularJS中获取Checkbox的所有选定对象?

Pri*_*nce 4 angularjs angular-ui angularjs-directive angularjs-scope angularjs-ng-repeat

我想使用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>
Run Code Online (Sandbox Code Playgroud)

我的控制器

  $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];
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

在这里,我将获得所有选定的项目$scope.selection.我怎么能得到它ng-model

是否可以这样做,ng-model="model.controller.object = selection" 因为我需要$scope.selection分配选定的model.controller.object

Moh*_*and 7

如果我理解正确你想要创建一个复选框并动态地将它绑定到列表中的项目,如果是这样,我将这样做:

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

});
Run Code Online (Sandbox Code Playgroud)

HTML:

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

插件.每当您选中复选框时,请在控制台中查看模型容器更改.

  • 好答案.如果您希望每个复选框都有自己唯一的变量,那么您实际上需要创建每个变量.这个答案中描述的方法就像它可以获得的那样干净利落. (2认同)