【问题标题】:How can I get all the selected objects of Checkboxes in AngularJS?如何获取 AngularJS 中复选框的所有选定对象?
【发布时间】:2014-02-20 05:32:19
【问题描述】:

我想使用 AngularJS 获取复选框的所有选定对象。

下面是我的代码

我的观点.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];
            }
        }
    }

这里我会得到$scope.selection中所有选中的项目。我怎样才能把它送到ng-model

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

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-scope angularjs-ng-repeat angular-ui


    【解决方案1】:

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

    $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。每当您选中复选框时,都会在控制台中查看模型容器的变化。

    【讨论】:

    • 这不是我的情况。请再次阅读我的问题。尤其是最后两行
    • 我确实阅读了你的问题,但我告诉你退后一步,重新考虑你想做什么,因为你要求的没有意义:)
    • 好答案。如果您希望每个复选框都有自己的唯一变量,那么您实际上需要创建每个变量。这个答案中描述的方法是尽可能干净的方法。
    • 这就像一个魅力。感谢您的回答。但是,有一个错误:当错误选择后取消选中复选框时,对象仍保持选中状态。如何解决这个问题?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-18
    • 1970-01-01
    • 2016-03-17
    • 1970-01-01
    • 2021-09-11
    • 2015-12-11
    • 1970-01-01
    相关资源
    最近更新 更多