要将复选框值绑定到 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) { // 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 ... }; }]);
优点:
缺点:
或者,您可以使用对象数组作为输入数据:
<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: [{ 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); }]);
优点:
缺点:
每个解决方案各有优点和缺点,因此选择最佳方法取决于您应用程序的具体要求。
以上是如何在 AngularJS 中有效地将复选框值绑定到列表?的详细内容。更多信息请关注PHP中文网其他相关文章!