我想要实现的是,当我选中“master”复选框时,选中属于 ng-repeat
循环迭代的一些复选框。到目前为止我的代码在 View 中:
<div ng-app="CheckAllModule">
<div ng-controller="checkboxController">
<ul ng-repeat="s in struct">
<li><strong>{{s}} item</strong>
<input type="checkbox" ng-checked="x1 && x2 && x3" ng-model="selectedAll" ng-click="checkAll()" />
</li>
<label>Subitem A
<input type="checkbox" ng-checked="chk" ng-model="x1" />
</label>
<label>Subitem B
<input type="checkbox" ng-checked="chk" ng-model="x2" />
</label>
<label>Subitem C
<input type="checkbox" ng-checked="chk" ng-model="x3" />
</label>
</ul>
</div>
</div>
其中第一个复选框是“主”,并且应该将其自己的状态强加给“从”(接下来的三个复选框),无论它们之前的状态是什么。
关于从属复选框,应独立选中和取消选中它们。但如果三者同时检查的话,主人也应该如此。只要其中一个没有被检查,master 就不应该被检查。
还有我的 Controller :
var app = angular.module("CheckAllModule", []);
app.controller("checkboxController", function ($scope) {
$scope.struct = ['First', 'Second'];
$scope.checkAll = function () {
if ($scope.selectedAll) {
$scope.chk = true;
} else {
$scope.chk = false;
}
};
});
最佳答案
这几乎肯定不符合最佳实践,但我是 Angular 的菜鸟。但它确实有效:
http://plnkr.co/edit/oGNC3ZUZHDHrBrMyRKjW?p=preview
var app = angular.module("CheckAllModule", []);
app.controller("checkboxController", function($scope) {
$scope.struct = ['First', 'Second'];
$scope.checkAll = function(selected, chkArray) {
for (var chk in chkArray) {
chkArray[chk] = selected
}
};
});
我对您的 html 进行了一些调整以使其正常工作:
<div ng-app="CheckAllModule">
<div ng-controller="checkboxController">
<ul ng-repeat="s in struct" data-ng-init="x[1]=false;x[2]=false;x[3]=false">
<li>
<strong>{{s}} item</strong>
<input type="checkbox" ng-checked="x[1] && x[2] && x[3]" ng-model="selectedAll" ng-click="checkAll(selectedAll, x)" />
</li>
<label>Subitem A
<input type="checkbox" ng-model="x[1]" />
</label>
<label>Subitem B
<input type="checkbox" ng-model="x[2]" />
</label>
<label>Subitem C
<input type="checkbox" ng-model="x[3]" />
</label>
</ul>
</div>
</div>
更新
我正在考虑如何更好地测试 x1 && x2 && x3
转换为数组是第一步,但接下来你可以这样做:
x.indexOf(false)
(理想情况下,您会使用 .reduce(function(a,b) { return a && b; })
但 reduce
尚未得到足够的支持,无法公平,它有点笨重) - 奇怪的是这还不起作用。
关于javascript - 使用 AngularJS 选择同一循环迭代中的所有复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29970372/