我一直在玩Angular.js,並決定檢查所有複選框,一旦父複選框被選中,我已經使用ng-model
和ng-checked
指令。如何選擇基於angular.js中的子複選框的父複選框?
<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/
,我們可以使上面的代碼更穩健?
你有什麼期望,一旦你取消任何複選框的發生? –
我已經添加了上面的演示鏈接。一旦我檢查父複選框,它會檢查所有的子複選框。但是,當我取消選中某個選中的子複選框時,它應該取消選中父項複選框。 – codef0rmer
像所有的複選框應該同步? –