TIL : AngularJS, binding to a list of checkbox values

html :

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

controller :

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

source: http://stackoverflow.com/questions/14514461/how-can-angularjs-bind-to-list-of-checkbox-values

Leave a Reply