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