Table Multiple checkbox AngularJS

Table Multiple checkbox AngularJS

Here you will see how to create multiple checkbox in the table using AnuglarJS and control its behavior based on the selected events:

HTML code:

<!DOCTYPE html>
<html ng-app="App">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>
<meta charset=utf-8 />
<title>Table with multiple checkbox AngularJS</title>

<script type="text/javascript">

	var app = angular.module('App', []);
	app.controller('MainCtroller', function($scope) {	
	
	        $scope.model = {};
	
	        // This property will be bound to checkbox in table header
	        $scope.model.allItemsSelected = false;
	
	        // Here first initialize all name list
	        $scope.model.entities = [
	            { "key": 1, "value": "Java Honk" },
	            { "key": 2, "value": "Angular JS" },
	            { "key": 3, "value": "Multiple Check box" }
	        ];
	
	        // This executes when entity in table is checked
	        $scope.selectEntity = function () {
	            // If any entity is not checked, then uncheck the "allItemsSelected" checkbox
	            for (var i = 0; i < $scope.model.entities.length; i++) {
	                if (!$scope.model.entities[i].isChecked) {
	                    $scope.model.allItemsSelected = false;
	                    return;
	                }
	            }
	
	            //If not the check the "allItemsSelected" checkbox
	            $scope.model.allItemsSelected = true;
	        };
	
	        // This executes when checkbox in table header is checked
	        $scope.selectAll = function () {
	            // Loop through all the entities and set their isChecked property
	            for (var i = 0; i < $scope.model.entities.length; i++) {
	                $scope.model.entities[i].isChecked = $scope.model.allItemsSelected;
	            }
	        };
	  
	
	    
	});
  
</script>

</head>
<body ng-controller="MainCtroller">
<h3>Table With multiple checkbox AngularJS</h3>
	<table border="1">
    <thead>
        <tr>
            <th><input type="checkbox" ng-model="model.allItemsSelected" ng-change="selectAll()"></th>
            <th>Names</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="entity in model.entities" ng-class="{selected: entity.isChecked}">
            <td><input type="checkbox" ng-model="entity.isChecked" ng-change="selectEntity()"></td>
            <td>{{entity.value}}</td>
        </tr>
    </tbody>
</table>
</body>
</html>

Output:

Table Multiple checkbox AngularJS

 

Test in Plunker: Table Multiple checkbox AngularJS

For more information please read AngularJS API here

One thought on “Table Multiple checkbox AngularJS”

Leave a Reply

Your email address will not be published. Required fields are marked *