You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AngularJS ng-repeat下拉框限制重复选择问题求助

解决方案:限制新增下拉框选择已选中的值

我明白你的需求啦——要让新增的下拉框不能选之前已经被选过的选项,不管是隐藏还是禁用都可以。咱们来一步步把方案集成到你的代码里:

首先,咱们需要给每个下拉框的选中值做绑定,这样才能追踪哪些值已经被选了,再添加一个自定义过滤函数来排除已选选项。

修改后的完整代码

JavaScript 部分

var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function($scope) {
  $scope.names = ['Mobile','Office','Home'];
  // 给每个选项对象添加selectedName属性,用来存储当前下拉框的选中值
  $scope.choices = [{id: 'choice1', selectedName: null}];
  
  $scope.addNewChoice = function() {
    var newItemNo = $scope.choices.length+1;
    $scope.choices.push({'id':'choice'+newItemNo, selectedName: null});
  };
  
  // 自定义过滤函数:排除已被其他下拉框选中的值
  $scope.filterUsedNames = function(name, currentChoice) {
    // 检查是否有其他下拉框已经选中了当前name,且不是当前的下拉框本身
    return !$scope.choices.some(function(choice) {
      return choice !== currentChoice && choice.selectedName === name;
    });
  };
});

HTML 部分

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="angularjs-starter" ng-controller="MainCtrl">
  <fieldset ng-repeat="choice in choices">
    <!-- 把下拉框的选中值绑定到当前choice的selectedName属性 -->
    <select ng-model="choice.selectedName">
      <!-- 使用自定义过滤函数,只显示未被其他下拉框选中的选项 -->
      <option 
        ng-repeat="x in names | filter: (name) => filterUsedNames(name, choice)"
        value="{{x}}">
        {{x}}
      </option>
    </select>
  </fieldset>
  <button class="addfields" ng-click="addNewChoice()">Add fields</button>
</div>

关键部分解释

  1. 绑定选中状态:给每个choice对象新增selectedName属性,这样每个下拉框的选中值都会被单独存储,方便后续追踪已选内容。
  2. 自定义过滤逻辑:filterUsedNames函数会判断当前选项是否已经被其他下拉框选中(排除当前下拉框自己的选择,这样修改当前下拉框时不会把自己的选项隐藏)。
  3. 过滤显示选项:在选项的ng-repeat中应用这个过滤函数,只展示未被选中的选项。

如果更偏好禁用已选选项而非隐藏,只需要修改HTML中的option部分,用ng-disabled替代过滤即可:

<option 
  ng-repeat="x in names"
  value="{{x}}"
  ng-disabled="!filterUsedNames(x, choice)">
  {{x}}
</option>

这样已被选中的选项会变成灰色不可选状态,保留视觉展示但无法选择。

内容的提问来源于stack exchange,提问作者user9130953

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:39:33