In this article I will explain with an example, how to select single CheckBox between multiple CheckBoxes using AngularJS.
Single selection functionality amongst CheckBoxes is also known as Mutually Exclusive CheckBoxes as at a time only one CheckBox can be checked while the other checked CheckBox will be automatically unchecked.
Select single CheckBox between multiple CheckBoxes using AngularJS
The below HTML Markup consists of an HTML DIV to which ng-app and ng-controller AngularJS directives have been assigned.
The AngularJS app HTML DIV consists of another HTML DIV with a CheckBox and Label elements. The ng-repeat directive has been applied to the HTML DIV in order to populate CheckBoxList i.e. List of multiple CheckBoxes from a JSON array.
The ng-model attribute of the CheckBox has been assigned the Selected property. Thus whenever a CheckBox is selected, the Selected property for the corresponding object in the JSON array will be set to TRUE.
The CheckBox has been assigned ng-change directive. When the CheckBox is checked, the CheckBox_Checked function of the Controller gets called.
Inside the function, a loop is executed over the JSON array and the FruitId of the selected (checked) CheckBox is matched with all the items of the JSON Array and the Selected property of all items except the selected (checked) CheckBox is set to False.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $window) {
$scope.Fruits = [{
FruitId: 1,
Name: 'Mango',
Selected: false
}, {
FruitId: 2,
Name: 'Apple',
Selected: false
}, {
FruitId: 3,
Name: 'Banana',
Selected: false
}, {
FruitId: 4,
Name: 'Guava',
Selected: false
}, {
FruitId: 5,
Name: 'Orange',
Selected: false
}];
$scope.CheckBox_Checked = function (selectedFruitId) {
for (var i = 0; i < $scope.Fruits.length; i++) {
if ($scope.Fruits[i].FruitId != selectedFruitId) {
$scope.Fruits[i].Selected = false;
}
}
}
});
</script>
<div ng-app="MyApp" ng-controller="MyController">
<div ng-repeat="fruit in Fruits">
<label for="chkCustomer_{{fruit.FruitId}}">
<input id="chkCustomer_{{fruit.FruitId}}" type="checkbox" ng-model="fruit.Selected" ng-change = "CheckBox_Checked(fruit.FruitId)" />
{{fruit.Name}}
</label>
</div>
</div>
</body>
</html>
Screenshot
Demo
Downloads