绑定到 AngularJS 中的复选框值列表
要将多个复选框值与控制器中的列表关联,有两种主要方法:利用简单数组或对象数组。
使用简单数组
在 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) { $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); }; }]);
优点:
缺点:
使用对象数组
在 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) { $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); }]);
优点:
缺点:
附加说明:
以上是如何在 AngularJS 中有效地将复选框值绑定到列表?的详细内容。更多信息请关注PHP中文网其他相关文章!