要將復選框值綁定到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中文網其他相關文章!