AngularJS directive to manage Checkbox list

Browsing the web to find a solution to maintain a list of data bind to a list of checkbox in an AngularJS view, I’ve found the following plunker proposing a very good solution, working in most of the cases.

Here is the directive :

app.directive('checkList', function() {
  return {
    scope: {
      list: '=checkList',
      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.$watch('list', setupHandler, true);

Here is the html view side :

<div ng-app="myApp" ng-controller='MainController'>
  <span ng-repeat="fruit in fruits">
    <input type='checkbox' value="{{fruit}}" check-list='checked_fruits'> {{fruit}}<br />

  <div>The following fruits are checked: {{checked_fruits | json}}</div>

  <div>Add fruit to the array manually:
    <button ng-repeat="fruit in fruits" ng-click='addFruit(fruit)'>{{fruit}}</button>

And the Angular Controller to manager the page :

app.controller('MainController', function($scope) {
  $scope.fruits = ['apple', 'orange', 'pear', 'naartjie'];
  $scope.checked_fruits = ['apple', 'pear'];
  $scope.addFruit = function(fruit) {
    if ($scope.checked_fruits.indexOf(fruit) != -1) return;

Thanks to Brandon Tilley for such a beautiful piece of code 🙂

Have Fun !



Les commentaires sont fermés.

Propulsé par

Retour en haut ↑

%d blogueurs aiment cette page :