我有几个复选框:
<input type='checkBox' value="apple" checked> <input type='checkBox' value="orange"> <input type='checkBox' value="pear" checked> <input type='checkBox' value="naartjie">
我想绑定到我的控制器中的列表,使得每当一个复选框被改变时,控制器维护所有被检查的值的列表,例如[‘apple’,’pear’]。
ng-model似乎只能将一个复选框的值绑定到控制器中的变量。
有另一种方法来做,使我可以绑定四个复选框到控制器中的列表?
有两种方法来处理这个问题。使用简单的数组或对象数组。每个解决方案都有它的利弊。下面你会找到一个每个案件。
用一个简单的数组作为输入数据
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); // Is currently selected if (idx > -1) { $scope.selection.splice(idx,1); } // Is newly selected else { $scope.selection.push(fruitName); } }; }]);
优点:简单的数据结构和按名称切换容易处理
缺点:添加/删除是麻烦的,因为必须管理两个列表(输入和选择)
用对象数组作为输入数据
HTML可能如下所示:
<label ng-repeat="fruit in fruits"> <!-- - Use `value="{{fruit.name}}"` to give the input a real value,in case the form gets submitted traditionally - Use `ng-checked="fruit.selected"` to have the checkBox checked based on some angular expression (no two-way-data-binding) - Use `ng-model="fruit.selected"` to utilize two-way-data-binding. Note that `.selected` is arbitrary. The property name could be anything and will be created on the object if not present. --> <input type="checkBox" name="selectedFruits[]" value="{{fruit.name}}" ng-model="fruit.selected" > {{fruit.name}} </label>
并且适当的控制器代码将是:
app.controller('ObjectArrayCtrl','filterFilter',function ObjectArrayCtrl($scope,filterFilter) { // Fruits $scope.fruits = [ { name: 'apple',selected: true },{ name: 'orange',selected: false },{ name: 'pear',{ name: 'naartjie',selected: false } ]; // Selected fruits $scope.selection = []; // Helper method to get 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); }]);