Binding to a List of Checkbox Values in AngularJS
To associate multiple checkbox values with a list in the controller, there are two primary approaches: utilizing a simple array or an array of objects.
Using a Simple Array
In the 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>
In the controller:
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); idx > -1 ? $scope.selection.splice(idx, 1) : $scope.selection.push(fruitName); }; }]);
Advantages:
Disadvantages:
Using an Array of Objects
In the HTML:
<label ng-repeat="fruit in fruits"> <input type="checkbox" name="selectedFruits[]" value="{{fruit.name}}" ng-model="fruit.selected" > {{fruit.name}} </label>
In the controller:
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); }]);
Advantages:
Disadvantages:
Additional Notes:
The above is the detailed content of How to Efficiently Bind Checkbox Values to a List in AngularJS?. For more information, please follow other related articles on the PHP Chinese website!