AngularJS中如何根据已选值过滤其余下拉选择框的选项?
解决AngularJS动态Select框互斥选项问题
核心思路
要实现选中值从其他Select框选项中移除,关键是让每个Select框的选项列表排除其他已选中的值,但保留自身当前选中的值——这样既保证选项不重复,又不会出现刚选中就从当前框消失的问题。
完整代码实现
HTML部分
<body ng-app="myNgApp"> <div ng-controller="myController"> <input type="button" value="Add group" ng-if="availableGroups < allGroups.length" ng-click="addGroup()" /> <input type="button" value="Remove group" ng-click="removeGroup()" ng-if="availableGroups > 0" /> <div ng-repeat="group in [].constructor(availableGroups) track by $index"> <select ng-model="selectedGroups[$index]" ng-options="col for col in getAvailableOptions($index)" ></select> </div> </div> </body>
JavaScript部分
var ngApp = angular.module('myNgApp', []); ngApp.controller('myController', function($scope) { $scope.allGroups = ['group 1', 'group 2', 'group 3', 'group 4', 'group 5']; $scope.availableGroups = 0; $scope.selectedGroups = []; // 存储每个Select框的选中值 // 添加Select框 $scope.addGroup = function() { $scope.availableGroups += 1; // 初始化新增框的选中值为undefined $scope.selectedGroups.push(undefined); }; // 移除最后一个Select框 $scope.removeGroup = function() { if ($scope.availableGroups <= 0) return; // 清空对应选中值,避免残留影响其他框 $scope.selectedGroups.pop(); $scope.availableGroups -= 1; }; // 获取当前Select框的可用选项 $scope.getAvailableOptions = function(currentIndex) { return $scope.allGroups.filter(group => { // 保留自身当前选中的值,排除其他已选中的值 return group === $scope.selectedGroups[currentIndex] || !$scope.selectedGroups.includes(group); }); }; });
关键细节说明
- 选中值存储:用
selectedGroups数组对应每个Select框的选中状态,索引与ng-repeat的$index一一对应。 - 选项过滤逻辑:
getAvailableOptions函数通过filter实现:- 如果当前选项是当前Select框已选中的值,保留
- 如果当前选项未被其他任何Select框选中,保留
- 移除框的处理:移除时同步清空
selectedGroups中对应位置的值,避免已选值残留导致其他框选项异常。 - 边界控制:给"Remove group"按钮加
ng-if="availableGroups > 0",防止移除到负数。
原方案失效原因
你之前尝试的方式是把所有已选值从选项中排除,包括当前Select框自己选中的那个值——所以选中后,当前框的选项列表里就找不到这个值了,自然会消失。现在的过滤逻辑特意保留了当前框的选中值,就解决了这个问题。
内容的提问来源于stack exchange,提问作者Tasos
相关产品推荐
相关产品推荐

