防止用户在多个下拉列表中选择相同的值

时间:2019-04-15 19:55:33

标签: angularjs

我正在从API调用加载表,表行是动态的,它基于API调用返回的值。我正在显示排序顺序,并且值应该是唯一的,并且用户不应选择先前选择的值。我尝试按照此(http://jsfiddle.net/jnash21/oqezom4y/)进行操作,但是由于我的动态,我无法实现。

我尝试了这个(http://embed.plnkr.co/QU4r05n9rQprwyL9Ltxh/)。

editor.controller('EditorController', function($scope) {

  $scope.entities = [{name:"pencil",sortOrder:""} ,{name:"notepad",sortOrder:""} ,
  {name:"bookshelf",sortOrder:""}
  ];

  $scope.sortOrderValues=[1,2,3];
});

    <table>
  <tr ng-repeat="x in entities">
    <td>{{ x.name }}</td>
    <td><select ng-model="x.sortOrder"
                ng-options="col for col in sortOrderValues"> 
       </select>
          <span ng-show="!x.sortOrder"> * sort order required</span>  
    </td>

  </tr>
</table>

如何防止用户使用angular js在每一行中选择相同的排序顺序?

1 个答案:

答案 0 :(得分:1)

plunker可能会对您有所帮助。

首先,生成一个从1到entities.length的数组(本例为3)。 选择选项时,触发optionSelected函数。此函数将生成您的初始数组,并由您的sortOrders计算使用的entities。然后从第一个数组中过滤出第二个。

HTML

<div ng-controller="EditorController">
  <table>
    <tr ng-repeat="x in entities">
      <td>{{ x.name }}</td>
      <td><select ng-model="x.sortOrder"
                  ng-options="col for col in sortOrderValues"
                  ng-change="optionSelected()"> 
         </select>
            <span ng-show="!x.sortOrder"> * sort order required</span>  
      </td>

    </tr>
  </table>
</div>

CONTROLLER

editor.controller('EditorController', function($scope) {

  $scope.entities = [{name:"pencil",sortOrder:""} ,{name:"notepad",sortOrder:""} ,
  {name:"bookshelf",sortOrder:""}
  ];

  // Genereate all the numbers between 1 and $scope.entities.length
  $scope.sortOrderValues= $scope.entities.map(
    function (item, index) {
      return index + 1;
    }
  );

  // Function executed when you select a sortOrder
  $scope.optionSelected = function () {
    // Genereate all the numbers between 1 and $scope.entities.length
    var allIndexes = $scope.entities
      .map(function (entity, index) { return index + 1; });

    // Get all the sortOrder used
    var usedIndexes = $scope.entities
      .map(function(e) { return e.sortOrder; });

    // Remove from the [1, .., $scope.entities.length] array all the sortOrder used
    $scope.sortOrderValues = allIndexes
      .filter(function (order) {
        return !usedIndexes.find(function(index) { return index === order; });
      });
  }
});