This tutorial will explain how to achieve check all and uncheck all checkbox using angularjs and listing all checked values in the page. Find the demo and download the source code at the end of the tutorial.
Let’s start our tutorial
Find the folder structure
Select all and Unselect all checkbox
Create index.html and include the below code
<html>
<head>
<title>Check and Uncheck in check box in angularjs</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.3.2/angular-ui-router.js"></script>
<script src="js/controller.js"></script>
</head>
<body ng-app="appModule" ng-controller="mainController">
<div ui-view></div>
</body>
</html>
In above code you can find <div ui-view></div> and controller.js and include the angular dependency.
<div ui-view></div> will initiate the default page which is defined in controller.js.
In controller file include the below code
var app = angular.module('appModule',['ui.router']);
app.config(function($stateProvider){
$stateProvider.state('home',{
url:'/',
templateUrl:'templates/mainPage.html'
});
});
app.controller('mainController',['$scope','$state',function($scope,$state){
$state.go("home");
$scope.allOption = "All";
var modelScope = {
"checkboxModel" : "checkboxModel",
"selectedItems" : "selectedItems"
};
$scope.data = ["checkBox1","checkBox2","checkBox3"];
$scope.checkboxModel = [];
$scope.selectedItems = [];
$scope.onClickFn = function(val){
if(val == $scope.allOption)
resultsFnAll();
else
addorRemoveItems(val);
};
function addorRemoveItems(val){
if($scope[modelScope.checkboxModel][val]){
$scope[modelScope.selectedItems].push(val);
}else if(!$scope[modelScope.checkboxModel][val]){
$scope[modelScope.selectedItems].splice($scope[modelScope.selectedItems].indexOf(val), 1);
};
if($scope[modelScope.selectedItems].length >= ($scope.data.length))
$scope[modelScope.checkboxModel][$scope.allOption] = true;
else
$scope[modelScope.checkboxModel][$scope.allOption] = false;
};
function resultsFnAll(){
var allVal = $scope[modelScope.checkboxModel][$scope.allOption];
if(allVal)
$scope[modelScope.selectedItems] = angular.copy($scope.data);
else
$scope[modelScope.selectedItems] = [];
for (property in $scope["data"]) {
$scope[modelScope.checkboxModel][$scope["data"][property]] = allVal;
};
};
}]);
Include the below code in mainPage.html
<div ng-controller="mainController">
<ul class="list-group">
<li><input type="checkbox" ng-change="onClickFn(allOption)" ng-model="checkboxModel[allOption]" checked="checked"> {{allOption}}</li>
<li ng-repeat="item in data">
<input type="checkbox" ng-change="onClickFn(item)" ng-model="checkboxModel[item]" checked="checked"> {{item}}
</li>
</ul>
<h2>Selected Value</h2>
<li ng-repeat="val in selectedItems">{{val}}</li>
</div>
Leave a Reply