Create List of CheckBoxes in AngularJS
Posted By : Yasir Zuberi | 31-Dec-2014
This blog will explain you how you can create a list of CheckBoxes to store selected objects of an array in one model. I am using a directive Checklist-model which solves the task with less line of codes in controller.
First you need to download the js for Checklist-model
http://cdn.jsdelivr.net/angular.checklist-model/0.1.3/checklist-model.min.js
Now add a controller as below.
angular.module('check', ['checklist-model'])
.controller('controller', function($scope) {
//initilize an array of objects.
$scope.fruitsList = [
{id: 1, name: 'Apple'},
{id: 2, name: 'Mango'},
{id: 3, name: 'Banana'},
{id: 4, name: 'Guava'},
{id: 5, name: 'Orange'}
];
//create a blank array to store selected objects.
$scope.selected = {
fruits: []
};
//this functions copies all the fruitList objects into selected.fruits
$scope.checkAll = function() {
$scope.selected.fruits = angular.copy($scope.fruitsList);
};
//this function removes all the objects from selected.fruits
$scope.uncheckAll = function() {
$scope.selected.fruits = [];
};
});
Below is the code for html
<div ng-app="check">
<div ng-controller="controller">
<label ng-repeat="fruit in fruitsList">
<input type="checkbox" checklist-model="selected.fruits" checklist-value="fruit" /> {{fruit.name}}<br/> </label>
<button ng-click="checkAll()">Check all</button>
<button ng-click="uncheckAll()">Uncheck all</button> <br/>
{{selected.fruits}}
</div>
</div>
For better understanding I have created a working fiddle. Please try this Demo http://jsfiddle.net/yasirzuberi/r1Lc3ba0/4/
Note:- If you would like to store only id's or name's of selected objects. Definately you can do that without much change.
To save only id's of selected objects you just need to make two simple changes
1. html change
replace checklist-value="fruit" to checklist-value="fruit.id"
2. controller change
Edit checkAll function
replace angular.copy($scope.fruitsList); to $scope.fruitsList.map(function(item) { return item.id; });
//Similarly if you want to store names of objects, edit above changes with name instead if id. That's it.
Thanks,
Yasir
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Yasir Zuberi
Yasir is Lead Developer. He is a bright Java and Grails developer and have worked on development of various SaaS applications using Grails framework.