angularjs – 如何根据angular.js中的子复选框选择父复选框?

前端之家收集整理的这篇文章主要介绍了angularjs – 如何根据angular.js中的子复选框选择父复选框?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我最近一直在玩Angular.js并决定在选中父复选框后检查所有复选框,我已经使用ng-model和ng-checked指令完成了.

<div ng-app>
        <div ng-controller="Ctrl">
            <input type="checkBox" ng-model="parent"/> Select All<br/>
            <input type="checkBox" ng-model="child_1" ng-checked="parent" ng-click="getAllSelected()"/> First<br/>
            <input type="checkBox" ng-model="child_2" ng-checked="parent" ng-click="getAllSelected()"/> Second<br/>
            <input type="checkBox" ng-model="child_3" ng-checked="parent" ng-click="getAllSelected()"/> Three<br/>
            <input type="checkBox" ng-model="child_4" ng-checked="parent" ng-click="getAllSelected()"/> Four<br/>
            <input type="checkBox" ng-model="child_5" ng-checked="parent" ng-click="getAllSelected()"/> Five<br/>
        </div>
    </div>

现在,我正在尝试选中所有子复选框,一旦检查了所有子复选框但面临一些问题.

function Ctrl($scope) {
       $scope.getAllSelected = function () {
          var chkChild = document.querySelectorAll('input[ng-model^="child_"]').length;
          var chkChildChecked = document.querySelectorAll('input[ng-model^="child_"]:checked').length;
          if (chkChild === chkChildChecked) $scope.parent= true;
          else $scope.parent= false;
       }
    }

演示:http://jsfiddle.net/codef0rmer/QekpX/

我们可以使上面的代码更健壮吗?

解决方法

复选框中的ng-checked属性采用表达式.因此,您可以使用和/或条件给出表达式,如下所述,以便根据表达式进行检查.

<input type="checkBox" ng-checked="child_1 && child_2 && child_3 && child_4 && child_5" ng-model="parent"/> Select All<br/>

当单击每个子复选框时,您不必编写单独的函数来执行计算.

Here is example in jsfiddle

猜你在找的Angularjs相关文章