Binding Checkbox Values to a List with AngularJS

AngularJS provides several ways to bind checkbox values to a list, making it easier to manage multiple checkboxes and their corresponding values. In this tutorial, we will explore two common approaches: using a simple array as input data and using an object array as input data.

Using a Simple Array as Input Data

When working with a simple array, you can use the ng-repeat directive to iterate over the array and create checkboxes for each item. To bind the checkbox values to a list, you can use the ng-checked and ng-click directives.

Here is an example of how you can implement this approach:

<label ng-repeat="fruitName in fruits">
  <input type="checkbox" name="selectedFruits[]" value="{{fruitName}}" ng-checked="selection.indexOf(fruitName) > -1" ng-click="toggleSelection(fruitName)">
  {{fruitName}}
</label>

In the controller, you can define the fruits array and the selection array to store the checked values. You can also define a toggleSelection function to handle the checkbox clicks:

app.controller('SimpleArrayCtrl', ['$scope', function SimpleArrayCtrl($scope) {
  $scope.fruits = ['apple', 'orange', 'pear', 'naartjie'];
  $scope.selection = ['apple', 'pear'];

  $scope.toggleSelection = function toggleSelection(fruitName) {
    var idx = $scope.selection.indexOf(fruitName);

    if (idx > -1) {
      $scope.selection.splice(idx, 1);
    } else {
      $scope.selection.push(fruitName);
    }
  };
}]);

Using an Object Array as Input Data

When working with an object array, you can use the ng-repeat directive to iterate over the array and create checkboxes for each item. To bind the checkbox values to a list, you can use the ng-model directive.

Here is an example of how you can implement this approach:

<label ng-repeat="fruit in fruits">
  <input type="checkbox" name="selectedFruits[]" value="{{fruit.name}}" ng-model="fruit.selected">
  {{fruit.name}}
</label>

In the controller, you can define the fruits array and the selection array to store the checked values. You can also define a selectedFruits function to get the selected fruits:

app.controller('ObjectArrayCtrl', ['$scope', 'filterFilter', function ObjectArrayCtrl($scope, filterFilter) {
  $scope.fruits = [
    { name: 'apple', selected: true },
    { name: 'orange', selected: false },
    { name: 'pear', selected: true },
    { name: 'naartjie', selected: false }
  ];

  $scope.selection = [];

  $scope.selectedFruits = function selectedFruits() {
    return filterFilter($scope.fruits, { selected: true });
  };

  $scope.$watch('fruits|filter:{selected:true}', function (nv) {
    $scope.selection = nv.map(function (fruit) {
      return fruit.name;
    });
  }, true);
}]);

Using a Directive

You can also use a directive to bind checkbox values to a list. Here is an example of how you can implement this approach:

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.$apply(changeHandler);
      });
      scope.$watch('list', setupHandler, true);
    }
  };
});

You can then use the directive in your HTML:

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

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

In the controller, you can define the fruits array and the checked_fruits array to store the checked values:

app.controller('MainController', function($scope) {
  $scope.fruits = ['apple', 'orange', 'pear', 'naartjie'];
  $scope.checked_fruits = ['apple', 'pear'];
});

Conclusion

In this tutorial, we have explored three common approaches to binding checkbox values to a list with AngularJS: using a simple array as input data, using an object array as input data, and using a directive. Each approach has its pros and cons, and the choice of which one to use depends on your specific requirements.

Leave a Reply

Your email address will not be published. Required fields are marked *