How to Select / Deselect All Checkboxes using AngularJS

You have seen the example in Gmail and many other web applications where they allow users to select all checkbox items by simply clicking on “Select All” checkbox. I have also created a tutorial in jQuery which you can find here.

Today let’s create the same using AngularJS.

Our HTML goes like this:

1
2
3
4
5
6
<div ng-app="selectApp" ng-controller="selectAll">
<input type="checkbox" ng-click="toggleSelect()" /> Select All <br />
      <div ng-repeat="checkbox in checkboxes">
         <input type="checkbox" name="{{checkbox.name}}" value="{{checkbox.value}}" ng-click="clearParent()" ng-model="checkbox.selected">{{checkbox.label}}
      </div>
</div>

We need to define the root element view of the application by adding ng-app=”selectApp” attribute to DIV element, then we specify behavior to main toggle checkbox by adding ng-click=”toggleSelect()” directive, which will toggle the checkboxes we iterate using ng-repeat directive.

AnjularJS

Once we declare the controller, we can add checkbox attributes to $scope object. $scope.checkboxes = [] you can specify as many checkboxes you want. Next we add behavior to toggleSelect function, which is attached to ng-click directive in our HTML.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
angular.module("selectApp", []).controller("selectAll", function($scope){
    //specify checkboxes values to $scope objecct
    $scope.checkboxes = [
        {name:'check[]', value:"1", label: "This is Item 1", selected : false},
        {name:'check[]', value:"2", label: "This is Item 2", selected : false},
        {name:'check[]', value:"3", label: "This is Item 3", selected : false},
        {name:'check[]', value:"4", label: "This is Item 4", selected : false}
    ];

    //toggle all checkboxes
    $scope.toggleSelect = function(){
        angular.forEach($scope.checkboxes, function(item){
            item.selected = event.target.checked;
        });
    }

});

Demo