To bind checkbox values to a list in an AngularJS controller, you can leverage two distinct approaches:
In this approach, the HTML markup resembles:
<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 corresponding controller code handles the binding:
app.controller('SimpleArrayCtrl', ['$scope', function SimpleArrayCtrl($scope) { // Fruits: ['apple', 'orange', 'pear', 'naartjie'] $scope.fruits = ...; // Selected fruits: ['apple', 'pear'] $scope.selection = ...; // Toggle selection by fruit name $scope.toggleSelection = function toggleSelection(fruitName) { // ... code to manage selection ... }; }]);
Pros:
Cons:
Alternatively, you can employ an array of objects for the input data:
<label ng-repeat="fruit in fruits"> <input type="checkbox" name="selectedFruits[]" value="{{fruit.name}}" ng-model="fruit.selected" > {{fruit.name}} </label>
The controller logic remains as follows:
app.controller('ObjectArrayCtrl', ['$scope', 'filterFilter', function ObjectArrayCtrl($scope, filterFilter) { // Fruits: [{ name: 'apple', selected: true }, ...] $scope.fruits = ...; // Selected fruits: [/* fruit names */] $scope.selection = ...; // Helper method to filter selected fruits $scope.selectedFruits = function selectedFruits() { return filterFilter($scope.fruits, { selected: true }); }; // Watch `fruits` for changes $scope.$watch('fruits|filter:{selected:true}', function (nv) { // ... code to update `$scope.selection` ... }, true); }]);
Pros:
Cons:
Each solution offers its advantages and drawbacks, so selecting the best approach depends on the specific requirements of your application.
The above is the detailed content of How to Effectively Bind Checkbox Values to Lists in AngularJS?. For more information, please follow other related articles on the PHP Chinese website!