如何在我的情况下检查所有的复选框

How to check all checkbox in my case?

本文关键字:复选框 检查 情况下 我的      更新时间:2023-09-26

我试图检查所有的checkboxes在angular的方式。

我有以下代码:

 <div>
     <div class="checkbox">
          <input ng-click="checkAll =! checkAll" type="checkbox"/> check all
     </div>
     <div class="checkbox" ng-repeat="item in items">
          <input type="checkbox" ng-model="checkAll"/> {{item.title}}
     </div>
</div>

当我点击check all时,我能够检查所有的checkboxes,然而,如果我检查和取消检查单个checkbox, check all似乎不再适用于单个checkbox了。有人能帮我解决这个问题吗?非常感谢!

修订答:

使用指令替代另一个答案的方法:

app.directive('myCheckBox', function(){
  return {
    restrict: 'E',
    scope: {
      checkAll: '=',
    },
    template: '<input check-all="checkAll" type="checkbox" ng-model="check"/>',
    replace: true,
    link: function(scope) {
      scope.$watch('checkAll', function(newVal){
        scope.check = newVal;
      })
    },
  }
})

我将父作用域的checkAll传递给新指令的作用域,并为它添加了一个监视器。

砰砰作响


老答:

你可以使用$parent(将访问作用域的父作用域):

<input type="checkbox" ng-model="$parent.checkAll"/> {{item.title}}

砰砰作响

并且您应该将checkAll作为ng-model作为主复选框,而不是作为单击事件。

您遇到的问题是由于ngRepeat为每个重复创建一个作用域。

您没有显示您的$scope.items是什么样子的。如果它是一个原语数组,那就有问题了。ng-repeat将为每个从父作用域继承的项创建一个新的作用域。问题是,对于原语,它只是复制值,而失去了双向绑定。相反,将项设置为对象数组,如下所示:

$scope.items = [
  {name: 'a', checked: false}, 
  {name: 'b', checked: false}, 
  {name: 'c', checked: false}
];

你还应该为"Check All"复选框设置一个单独的变量。

$scope.checkAll = false;

现在创建一个函数来遍历所有项目并设置checked属性:

$scope.checkAllBoxes = function(){
    $scope.checkAll = !$scope.checkAll;
    angular.forEach($scope.items, function(item){
      item.checked = $scope.checkAll;
    })
}

像这样把它们绑起来:

<div class="checkbox">
      <input type="checkbox" ng-click="checkAllBoxes()" /> check all
</div>
<div class="checkbox" ng-repeat="item in items">
      <input type="checkbox" ng-model="item.checked"/> {{item.name}}
</div>
演示