In this article I will explain with an example, how to build a CheckBoxList i.e. List of multiple CheckBoxes in AngularJS.
The CheckBoxList i.e. List of multiple CheckBoxes will be populated from a JSON array using the ng-repeat directive in AngularJS.
Populate list of multiple CheckBoxes using ng-repeat in 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 Button has been assigned ng-click directive. When the Button is clicked, the GetValue function of the Controller gets called.
Inside the function, a loop is executed over the JSON array and the Selected property is checked. If the Selected property is TRUE, it resembles that CheckBox is checked.
Finally the Fruit Id and Name of all the selected CheckBoxes are displayed using JavaScript Alert Message Box.
<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: 'Apple',
Selected: false
}, {
FruitId: 2,
Name: 'Mango',
Selected: false
}, {
FruitId: 3,
Name: 'Orange',
Selected: false
}];
$scope.GetValue = function () {
var message = "";
for (var i = 0; i < $scope.Fruits.length; i++) {
if ($scope.Fruits[i].Selected) {
var fruitId = $scope.Fruits[i].FruitId;
var fruitName = $scope.Fruits[i].Name;
message += "Value: " + fruitId + " Text: " + fruitName + "\n";
}
}
$window.alert(message);
}
});
</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" />
{{fruit.Name}}
</label>
</div>
<br />
<br />
<input type="button" value="Get" ng-click="GetValue()" />
</div>
</body>
</html>
Screenshot
Demo
Downloads