首页 > 解决方案 > Angularjs ng-repeat 从多个选择框中删除选定的选项

问题描述

使用 ng-repeat am 加载多个选择下拉元素,并且每个下拉列表都加载了相同的一组值。一旦用户从选择框中选择了一个选项;所选选项不应出现在其他选择框(选项)中。

示例:如果用户从select中选择选项A:1;然后在 select: 2 或任何其他 select: N 选项 A 不应该出现,反之亦然。

Plunker:https ://plnkr.co/edit/yCFIanCXPece49dk?open=lib%2Fscript.js&deferRun=1&preview

代码:

 <option ng-repeat="option in data.availableOptions | filter:arrayFilter(select.selectedOption,$index)" value="{{option.id}}">

   $scope.arrayFilter = function(selectionArray, position) {
    return function(item, index) {
      return selectionArray.indexOf(item.id) == -1 || item.id == selectionArray[position];
    }
  }

标签: javascriptangularjs

解决方案


您可以使用函数获取嵌套 ng-repeat 的选项,然后过滤掉不是当前选项并被选中的选项:

html:

<select name="repeatSelect{{$index}}" id="repeatSelect{{$index}}" ng-model="select.selectedOption">
  <option
    ng-repeat="option in getAvailableOptions(select.selectedOption)"
    value="{{option.id}}"
  >
    {{option.name}}
  </option>
</select>

控制器:

$scope.getAvailableOptions = function(current) {
  return this.data.availableOptions.filter((o) => o.id === current || !this.data.availableSelect.some(s => s.selectedOption === o.id));
};

这是一个分叉的plunker


推荐阅读