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:HTML
- 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>
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.ANJULARJS
- 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;
});
}
});