In this example, I will show you to create list of all week days with the check boxes using AngularJs.
Angular Directive
Create a new directive as follows:
var app = angular.module('app'); app.directive('weekDaysList', [weekDaysList]); function weekDaysList() { return { template: '<div style="padding:5px">' + '<div ng-repeat="option in weekDays">' + '<label class="clear">' + '<input type="checkbox" style=" width:22px; height:22px; font-size:12px;"' + 'class="radio-week-day" ng-model="option.ngValue">' + ' {{option.name}}</label></div>' + '</div>', restrict: 'A', replace: true, scope: { weekDays: "=" }, link: function(scope, element) { /** * @ngdoc method * @name destroy * @description * # utterly destroy listeners and anything else */ } }; }
The above is the simple directive but I want to explain one thing(scope declaration) which is as follows.
scope: { weekDays: "=" },
= binds a local/directive scope property to a parent scope property that means = binding is for two-way model binding. The model in parent scope is linked to the model in the directive’s isolated scope. Changes to one model affects the other, and vice versa.
So we can define ‘weekDays’ in our controller.
How to use ‘weekDaysList’ directive
You need to write the following html statement in your html:
<div week-Days-List week-days="weekDays"></div>
And in the controller set the list of all days of the week to ‘weekDays’ scope variable:
$scope.weekDays = [{ name: "Monday", value: true, }, { name: "Tuesday", value: true, }, { name: "Wednesday", value: true, }, { name: "Thursday", value: true, }, { name: "Friday", value: true, }, { name: "Saturday", value: true, }, { name: "Sunday", value: false, }, ];
How to get the list of selected days
This is very easy to obtain the list of the selected days. You can do this as below:
var i = 0, selectedDays = ""; for (i; i < $scope.weekDays.length; i++) { if ($scope.weekDays[i].value) { selectedDays = selectedDays + " " + $scope.weekDays[i].name; } } $scope.selectedDays = selectedDays;
You can check the above example with output on Plunker .