[英]Select All Checkbox in AngularJS
我有一個選擇所有復選框和列表復選框這樣。
復選框列表從中接收數據
$scope.contacts = [
{"name": "Bambizo", "check": false},
{"name": "Jimmy", "check": false},
{"name": "Tommy", "check": false},
{"name": "Nicky", "check": false}
];
我想當我選中一個全選復選框時,它會使下面列表中的所有復選框都被選中或取消選中。 在這里我的代碼:
選擇所有復選框:
<input type="checkbox" ng-model="checkAllContact" ng-change="checkAllContact(checkAllContact)">
checkAllContact函數:
$scope.checkAllContact = function(){
var allChecked = false;
for(i = 0; i< $scope.contacts.length; i++){
if ($scope.contacts[i].check == true){
allChecked = true;
}else {
allChecked = false;
}
}
if (allChecked = true){
for(i = 0; i< $scope.contacts.length; i++){
$scope.contacts[i].check = false;
}
}else{
for(i = 0; i< $scope.contacts.length; i++){
$scope.contacts[i].check = true;
}
}
}
但是當我運行並單擊全選復選框時。 它出錯了:
如何解決或有任何其他方法去做? 謝謝
ng-model="checkAllContact"
和方法checkAllContact
具有相同的名稱。
checkAllContact
范圍變量由checkAllContact
覆蓋。
您需要更改您的功能名稱才能解決問題。
您的函數名稱和變量名稱(ng-model)都相同,請更改其中一個。
你也可以用更簡單的方式來做,例如。
HTML:
<input type="checkbox" ng-model="checkAllContact1" ng-change="checkAllContact()">
<div ng-repeat="item in contacts">
<input type="checkbox" ng-model="item.check"/>
</div>
JS:
$scope.checkAllContact = function(){
if ($scope.checkAllContact1) {
$scope.checkAllContact1 = true;
} else {
$scope.checkAllContact1 = false;
}
angular.forEach($scope.contacts, function (item) {
item.check = $scope.checkAllContact1;
});
}
參見示例小提琴
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.