綁定到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); }; }]);
在控制器中:
優點:
簡單按名稱切換
缺點:<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中文網其他相關文章!