我最近一直在玩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>
Run Code Online (Sandbox Code Playgroud)
现在,我正在尝试选中所有子复选框,一旦检查了所有子复选框但面临一些问题.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
演示: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/>
Run Code Online (Sandbox Code Playgroud)
当单击每个子复选框时,您不必编写单独的函数来执行计算.
| 归档时间: |
|
| 查看次数: |
7273 次 |
| 最近记录: |