How do I bind to list of checkbox values with AngularJS?

how to get value of multiple checkbox in angularjs
get all checked checkbox value in angularjs
angularjs checkbox example
angularjs check if checkbox is checked
checkbox in angularjs w3schools
angular checkbox list
checklist-model angular 6
angularjs ng-repeat checkbox checked

I have a few checkboxes:

<input type='checkbox' value="apple" checked>
<input type='checkbox' value="orange">
<input type='checkbox' value="pear" checked>
<input type='checkbox' value="naartjie">

That I would like to bind to a list in my controller such that whenever a checkbox is changed the controller maintains a list of all the checked values, for example, ['apple', 'pear'].

ng-model seems to only be able to bind the value of one single checkbox to a variable in the controller.

Is there another way to do it so that I can bind the four checkboxes to a list in the controller?


There are two ways to approach this problem. Either use a simple array or an array of objects. Each solution has it pros and cons. Below you'll find one for each case.


With a simple array as input data

The HTML could look like:

<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>

And the appropriate controller code would be:

app.controller('SimpleArrayCtrl', ['$scope', function SimpleArrayCtrl($scope) {

  // Fruits
  $scope.fruits = ['apple', 'orange', 'pear', 'naartjie'];

  // Selected fruits
  $scope.selection = ['apple', 'pear'];

  // Toggle selection for a given fruit by name
  $scope.toggleSelection = function toggleSelection(fruitName) {
    var idx = $scope.selection.indexOf(fruitName);

    // Is currently selected
    if (idx > -1) {
      $scope.selection.splice(idx, 1);
    }

    // Is newly selected
    else {
      $scope.selection.push(fruitName);
    }
  };
}]);

Pros: Simple data structure and toggling by name is easy to handle

Cons: Add/remove is cumbersome as two lists (the input and selection) have to be managed


With an object array as input data

The HTML could look like:

<label ng-repeat="fruit in fruits">
  <!--
    - Use `value="{{fruit.name}}"` to give the input a real value, in case the form gets submitted
      traditionally

    - Use `ng-checked="fruit.selected"` to have the checkbox checked based on some angular expression
      (no two-way-data-binding)

    - Use `ng-model="fruit.selected"` to utilize two-way-data-binding. Note that `.selected`
      is arbitrary. The property name could be anything and will be created on the object if not present.
  -->
  <input
    type="checkbox"
    name="selectedFruits[]"
    value="{{fruit.name}}"
    ng-model="fruit.selected"
  > {{fruit.name}}
</label>

And the appropriate controller code would be:

app.controller('ObjectArrayCtrl', ['$scope', 'filterFilter', function ObjectArrayCtrl($scope, filterFilter) {

  // Fruits
  $scope.fruits = [
    { name: 'apple',    selected: true },
    { name: 'orange',   selected: false },
    { name: 'pear',     selected: true },
    { name: 'naartjie', selected: false }
  ];

  // Selected fruits
  $scope.selection = [];

  // Helper method to get selected fruits
  $scope.selectedFruits = function selectedFruits() {
    return filterFilter($scope.fruits, { selected: true });
  };

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

Pros: Add/remove is very easy

Cons: Somewhat more complex data structure and toggling by name is cumbersome or requires a helper method


Demo: http://jsbin.com/ImAqUC/1/

Checklist-model, But in practice we usually want one model to store array of checked values from several checkboxes. Checklist-model solves that task without additional code in  That I would like to bind to a list in my controller such that whenever a checkbox is changed the controller maintains a list of all the checked values, for example, ['apple', 'pear']. ng-model seems to only be able to bind the value of one single checkbox to a variable in the controller.


A simple solution:

<div ng-controller="MainCtrl">
  <label ng-repeat="(color,enabled) in colors">
      <input type="checkbox" ng-model="colors[color]" /> {{color}} 
  </label>
  <p>colors: {{colors}}</p>
</div>

<script>
  var app = angular.module('plunker', []);

  app.controller('MainCtrl', function($scope){
      $scope.colors = {Blue: true, Orange: true};
  });
</script>

http://plnkr.co/edit/U4VD61?p=preview

AngularJS Bind Array List to Checkboxes Example, Keywords : Angularjs bind checkboxes with ng-repeat example, Angularjs bind list of checkbox values example, Angularjs checkbox bind to array list example,  ng-model seems to only be able to bind the value of one single checkbox to a variable in the controller. Is there another way to do it so that I can bind the four checkboxes to a list in the controller?


<input type='checkbox' ng-repeat="fruit in fruits"
  ng-checked="checkedFruits.indexOf(fruit) != -1" ng-click="toggleCheck(fruit)">

.

function SomeCtrl ($scope) {
    $scope.fruits = ["apple, orange, pear, naartjie"];
    $scope.checkedFruits = [];
    $scope.toggleCheck = function (fruit) {
        if ($scope.checkedFruits.indexOf(fruit) === -1) {
            $scope.checkedFruits.push(fruit);
        } else {
            $scope.checkedFruits.splice($scope.checkedFruits.indexOf(fruit), 1);
        }
    };
}

How do I bind to list of checkbox values with AngularJS?, You can bind to a list of checkbox values with AngularJS with a simple array as input data. Looking for Angularjs material from basics! Refer to  That I would like to bind to a list in my controller such that whenever a checkbox is changed the controller maintains a list of all the checked values, for example, ['apple', 'pear']. ng-model seems to only be able to bind the value of one single checkbox to a variable in the controller.


Here's a quick little reusable directive that seems to do what you're looking to do. I've simply called it checkList. It updates the array when the checkboxes change, and updates the checkboxes when the array changes.

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);
    }
  };
});

Here's a controller and a view that shows how you might go about using it.

<div ng-app="myApp" ng-controller='MainController'>
  <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>

  <div>Add fruit to the array manually:
    <button ng-repeat="fruit in fruits" ng-click='addFruit(fruit)'>{{fruit}}</button>
  </div>
</div>
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;
    $scope.checked_fruits.push(fruit);
  };
});

(The buttons demonstrate that changing the array will also update the checkboxes.)

Finally, here is an example of the directive in action on Plunker: http://plnkr.co/edit/3YNLsyoG4PIBW6Kj7dRK?p=preview

input[checkbox], input[checkbox] HTML checkbox. Assignable AngularJS expression to data-​bind to. The value to which the expression should be set when selected. < input type = 'checkbox' value = "apple" checked > < input type = 'checkbox' value = "orange" > < input type = 'checkbox' value = "pear" checked > < input type = 'checkbox' value = "naartjie" > That I would like to bind to a list in my controller such that whenever a checkbox is changed the controller maintains a list of all the checked values, for example, ['apple', 'pear'] .


How do we bind to list of checkbox values with AngularJS, How do we bind to list of checkbox values with AngularJS - Simple data structure and toggling by name is easy to handle.It updates the array when the  Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. How to set selected checkbox in checkbox list based


AngularJS CheckBoxList example: Populate list of multiple , Populate list of multiple CheckBoxes using ng-repeat in AngularJS If the Selected property is TRUE, it resembles that CheckBox is checked. Stack Overflow Public questions and answers; Assigning ng-model to checkboxes generated by ng-repeat. How do I bind to list of checkbox values with AngularJS


Angularjs checkbox list From http://stackoverflow.com/questions , http://stackoverflow.com/questions/14514461/how-can-angularjs-bind-to-list-of-​checkbox-values #angularjs Either use a simple array or an array of objects. Here Mudassar Ahmed Khan has explained with an example, how to build a CheckBoxList i.e. List of multiple CheckBoxes in AngularJS. The CheckBoxList i.e. List of multiple CheckBoxes will be populated from a JSON array using the ng-repeat directive in AngularJS.


How To Bind To List Of Checkbox Values In AngularJS, Angularjs bind array list to checkboxes example. In angularjs we can bind array list to checkboxes using ng-repeat directive by looping through list of values