简介
处理一组复选框时,将它们的值绑定到控制器中的列表以进行有效管理至关重要。然而,AngularJS 的 ng-model 属性似乎仅限于绑定单个复选框值。本文探讨了解决此问题的两种方法,利用简单数组或对象数组作为输入数据。
方法 1:简单数组
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>
控制器:
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); } }; }]);
优点:
缺点:
方法 2:对象数组
HTML:
<label ng-repeat="fruit in fruits"> <input type="checkbox" name="selectedFruits[]" value="{{fruit.name}}" ng-model="fruit.selected" > {{fruit.name}} </label>
控制器:
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); }]);
优点:
缺点:
演示: http://jsbin.com/ImAqUC/1/
以上是如何在 AngularJS 中将多个复选框值绑定到列表?的详细内容。更多信息请关注PHP中文网其他相关文章!