我最近一直在玩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/
我们可以使上面的代码更健壮吗?