Pham Minh Tan
Pham Minh Tan

Reputation: 2096

Select All Checkbox in AngularJS

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

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:

Error when after click checkbox

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

Upvotes: 1

Views: 2291

Answers (2)

Zee
Zee

Reputation: 8488

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

Upvotes: 1

Pankaj Parkar
Pankaj Parkar

Reputation: 136184

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.

Upvotes: 2

Related Questions