Problem:
In AngularJS, a list of checkboxes is presented, and the objective is to establish a binding between them and a list in the controller. Each checked checkbox indicates the inclusion of its associated value in the list.
Solution:
AngularJS provides two viable solutions to this problem:
In this approach, the HTML structure mimics the checkbox list:
<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>
The accompanying controller code handles the interaction:
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); if (idx > -1) { $scope.selection.splice(idx, 1); } else { $scope.selection.push(fruitName); } }; }]);
Using an object array as the input data adds additional complexity but simplifies insertion and deletion operations:
<label ng-repeat="fruit in fruits"> <input type="checkbox" name="selectedFruits[]" value="{{fruit.name}}" ng-model="fruit.selected" > {{fruit.name}} </label>
The controller code reflects the change:
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 }); }; $scope.$watch('fruits|filter:{selected:true}', function (nv) { $scope.selection = nv.map(function (fruit) { return fruit.name; }); }, true); }]);
Advantages and Disadvantages:
Simple Array:
Object Array:
Demo: http://jsbin.com/ImAqUC/1/
The above is the detailed content of How to Bind AngularJS Checkboxes to a List of Values?. For more information, please follow other related articles on the PHP Chinese website!