Introduction
When dealing with a set of checkboxes, it can be crucial to bind their values to a list in the controller for effective management. However, AngularJS's ng-model property seems to be limited to binding a single checkbox value. This article explores two approaches to resolving this issue, leveraging either a simple array or an array of objects as input data.
Approach 1: Simple Array
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 $scope.toggleSelection = function toggleSelection(fruitName) { var idx = $scope.selection.indexOf(fruitName); if (idx > -1) { $scope.selection.splice(idx, 1); } else { $scope.selection.push(fruitName); } }; }]);
Pros:
Cons:
Approach 2: Object Array
HTML:
<label ng-repeat="fruit in fruits"> <input type="checkbox" name="selectedFruits[]" value="{{fruit.name}}" ng-model="fruit.selected" > {{fruit.name}} </label>
Controller:
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 for 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:
Cons:
Demo: http://jsbin.com/ImAqUC/1/
The above is the detailed content of How to Bind Multiple Checkbox Values to a List in AngularJS?. For more information, please follow other related articles on the PHP Chinese website!