【问题标题】:Angularjs ng-repeat remove selected option from multiple select boxesAngularjs ng-repeat 从多个选择框中删除选定的选项
【发布时间】:2020-12-24 21:39:00
【问题描述】:

使用 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];
    }
  }

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    您可以通过函数获取嵌套的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

    【讨论】:

    • 分叉 plunker 以包含空选择;如果用户想要重用/重置为选项值。 plnkr.co/edit/…
    猜你喜欢
    • 1970-01-01
    • 2019-07-20
    • 1970-01-01
    • 2016-12-11
    • 1970-01-01
    • 1970-01-01
    • 2019-04-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多