Select All Checkbox in AngularJS

本小妞迷上赌 提交于 2019-12-11 11:29:30

问题


I have a select all checkbox and list check-box like this.

A checkbox list receive data from

$scope.contacts = [
        {"name": "Bambizo", "check": false},
        {"name": "Jimmy", "check": false},
        {"name": "Tommy", "check": false},
        {"name": "Nicky", "check": false}
];

I want when i check a Select all checkbox, it make all checkbox in below list are checked or unchecked. And here my code:

Select All Checkbox:

<input type="checkbox" ng-model="checkAllContact" ng-change="checkAllContact(checkAllContact)">

checkAllContact function:

$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;
            }    
        }
    }

But when i run and click Select All checkbox. It make an error:

How to solve it or have any other way to do it? Thanks


回答1:


ng-model="checkAllContact" & method checkAllContact has same name.

checkAllContact scope variable is overriding by checkAllContact.

You need to change your function name will fix the issue.




回答2:


Your function name and variable name(ng-model) both are same, change one of them.

Also you can do it in a much simpler way, for an eg.

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;
    });
}

See the example Fiddle



来源:https://stackoverflow.com/questions/30120376/select-all-checkbox-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!