Tuesday, May 8, 2018

Handling multiple checkboxes with custom directive Angular JS

No comments
While dealing with check boxes you might have come across a scenario where you need to update the selection  of  a list of check boxes to a database and vice versa .

For example , I have a list of checkboxes which show if a particular color is selected or not. This selection is initially populated from the values in my database .  Based on the user selection I need to update the entries in my table by passing the selection to backend as a JSON i.e   ["Red","Pink","Yellow"] or as a comma separated string   Red,Pink,Yellow. 
Below is a reusable directive which can help us achieve this .This directive updates the array of selected checkboxes when the selection is changed and vice versa. 

app.directive('checkedList', function() {
    return {
        scope: {
            list: '=checkedList',
            value: '@'
        },
        link: function(scope, elem, attrs) {
            var handler = function(setup) {
                var checked = elem.prop('checked');
                var index = scope.list.indexOf(scope.value);
 
                if (checked && index == -1) {
                    if (setup) elem.prop('checked', false);
                    else scope.list.push(scope.value);
                } else if (!checked && index != -1) {
                    if (setup) elem.prop('checked', true);
                    else scope.list.splice(index, 1);
                }
            };
 
            var setupHandler = handler.bind(null, true);
            var changeHandler = handler.bind(null, false);
 
            elem.bind('change', function() {
                scope.$apply(changeHandler);
            });
            scope.$watch('list', setupHandler, true);
        }
    };
}); 

Here is the usage of this directive in a controller and view .

var app = angular.module('app',[])
.controller('myController', function myController( $scope ){
 
  $scope.colors = ["Red" , "White" ,"Pink", "Yellow","Green"]
  
  $scope.checked_colors = ["Red","Pink","Yellow"]
  
  
})

<div ng-app="app" ng-controller="myController">
    
         <span ng-repeat="color in colors">
             <input type='checkbox' value="{{color}}" 
                       checked-list='checked_colors'> {{color}}
             <br>
          </span>
</div>
 


Here is an example of the directive in action on Plunker: 



No comments :

Post a Comment