在Angular中为相同Items的其他Select Option字段禁用所选项

Jus*_*tin 2 angularjs angularjs-ng-repeat ng-options

我一直在努力奋斗......我目前正在使用Angular.

假设我们有五个选择选项字段,我们正在迭代每个选项字段的相同列表.

我们的选择是:

$scope.items = [one, two, three, four, five];
Run Code Online (Sandbox Code Playgroud)

如果我选择一个,如何禁用剩余选择选项字段的选定选项?如果我转到另一个选择选项字段并选择一个可用项目,则会为所有其他字段禁用该项目.

任何帮助甚至指导如何做到这一点将不胜感激.谢谢

rye*_*lar 7

您可能需要两种可能的解决方案,具体取决于您的规范要求的禁用类型.

  1. 通过删除已从其他select元素中选择的项目来禁用.此解决方案需要一个过滤器,用于删除已选择的项目,但当前select标记选择的当前项目除外.

DEMO

使用Javascript

  .controller('Ctrl', function($scope) {

    $scope.items = [1,2,3,4,5];
    $scope.data = [];

  })

  .filter('arrayDiff', function() {
    return function(array, diff) {
      var i, item, 
          newArray = [],
          exception = Array.prototype.slice.call(arguments, 2);

      for(i = 0; i < array.length; i++) {
        item = array[i];
        if(diff.indexOf(item) < 0 || exception.indexOf(item) >= 0) {
          newArray.push(item);
        }
      }

      return newArray;

    };
  });
Run Code Online (Sandbox Code Playgroud)

HTML

<select 
  ng-repeat="(modelIndex, itemValue) in items track by modelIndex"
  ng-model="data[modelIndex]"
  ng-options="item for item in $parent.items | arrayDiff:data:data[modelIndex]">
  <option value="">Select Number</option>
</select>
Run Code Online (Sandbox Code Playgroud)
  1. 通过将disabled属性设置为选项来禁用,这实际上是一种解决问题的复杂方法,因为它不使用标准的角度语法.通过使用a 迭代项目并添加一个表达式,该表达式将当前所选项目与其他元素中的其他所选项目进行评估.select ng-optionng-repeatng-disabledselect

DEMO

使用Javascript

  .controller('Ctrl', function($scope) {

    this.items = ['1', '2', '3', '4', '5'];
    this.data = [];

  })

  .filter('hasIntersection', function() {
    return function(item, array) {
      return array.indexOf(item) >= 0;
    };
  });
Run Code Online (Sandbox Code Playgroud)

HTML

<select
  ng-repeat="(selectIndex, itemValue) in Demo.items"
  ng-model="Demo.data[selectIndex]">

  <option value="" ng-selected="Demo.data[selectedIndex] == item">
    Select Number  
  </option>

  <option ng-repeat="item in Demo.items"
          value="{{item}}"
          ng-disabled="item | hasIntersection:Demo.data"
          ng-selected="Demo.data[selectIndex] == item">
    {{item}}
  </option>

</select>
Run Code Online (Sandbox Code Playgroud)