问题:
在 AngularJS 中,呈现一个复选框列表,并且目标是在它们和控制器中的列表之间建立绑定。每个选中的复选框都表示列表中包含其关联值。
解决方案:
AngularJS 针对此问题提供了两种可行的解决方案:
< ;h3>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 for a given fruit by name $scope.toggleSelection = function toggleSelection(fruitName) { var idx = $scope.selection.indexOf(fruitName); if (idx > -1) { $scope.selection.splice(idx, 1); } else { $scope.selection.push(fruitName); } }; }]);
使用对象数组作为输入数据会增加额外的复杂性,但会简化插入和删除操作:
<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 method to get selected fruits $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); }]);
优点和缺点:
简单数组:
对象数组:
演示: http://jsbin.com/ImAqUC/1/
以上是如何将 AngularJS 复选框绑定到值列表?的详细内容。更多信息请关注PHP中文网其他相关文章!