gpt4 book ai didi

angularjs - 选中/取消选中所有复选框 - AngularJS ng-repeat

转载 作者:行者123 更新时间:2023-12-01 09:54:33 26 4
gpt4 key购买 nike

我的结构如下所示:http://jsfiddle.net/deeptechtons/TKVH6/

<div>
<ul ng-controller="checkboxController">
<li>Check All
<input type="checkbox" ng-model="selectedAll" ng-click="checkAll()" />
</li>
<li ng-repeat="item in Items">
<label>{{item.Name}}
<input type="checkbox" ng-model="item.Selected" />
</label>
</li>
</ul>
</div>

angular.module("CheckAllModule", [])
.controller("checkboxController", function checkboxController($scope) {


$scope.Items = [{
Name: "Item one"
}, {
Name: "Item two"
}, {
Name: "Item three"
}];
$scope.checkAll = function () {
if ($scope.selectedAll) {
$scope.selectedAll = true;
} else {
$scope.selectedAll = false;
}
angular.forEach($scope.Items, function (item) {
item.Selected = $scope.selectedAll;
});

};


});

选中或取消选中所有复选框时,将选中所有其他复选框。 But when "Check All"is selected, and I deselect one of the items, I want "Check All"to be deselected.

提前致谢!

(PS:感谢 deeptechtons 的 JSFiddle)

最佳答案

如果您使用的是 Angular 1.3+,您可以使用 ng-model-options 中的 getterSetter 来解决这个问题并避免手动跟踪 allSelected状态

HTML:

<input type="checkbox" ng-model="allSelected" ng-model-options="{getterSetter: true}"/>

JS:

var getAllSelected = function () {
var selectedItems = $scope.Items.filter(function (item) {
return item.Selected;
});

return selectedItems.length === $scope.Items.length;
}

var setAllSelected = function (value) {
angular.forEach($scope.Items, function (item) {
item.Selected = value;
});
}

$scope.allSelected = function (value) {
if (value !== undefined) {
return setAllSelected(value);
} else {
return getAllSelected();
}
}

http://jsfiddle.net/2jm6x4co/

关于angularjs - 选中/取消选中所有复选框 - AngularJS ng-repeat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31010373/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com