从angularjs中的多个下拉列表中排除选定的选项?

时间:2015-03-07 18:27:05

标签: angularjs

我有五个下拉菜单。所有五个下拉菜单都有相同的选项来源。在一个下拉列表中选择的选项不应出现在剩余下拉列表的选项中。在angularjs中实现它的最佳方法是什么?

ng-options的来源是对象数组。

1 个答案:

答案 0 :(得分:3)

您需要提供适合您的特定需求和所需用户体验的实现,但这可能有助于您制定一些可以使用的基本原则。这只是我能想到的最小的例子。重点是您将过滤ng-options的自定义过滤器。它将接收您的对象数组(选项),并且您还将传入其他模型,以便您可以在选中它们时将其过滤掉。

在这里,我循环遍历每个选定的对象并将其从ng-options数组中删除,除非它是在此元素上选择的对象。

angular.module('myApp', [])
.filter('customFilter', function(filterFilter) {
  return function(input, filterEach, exclude) {
    filterEach.forEach(function(item) {
      if (angular.equals(item, exclude)) { return; }
      input = filterFilter(input, '!'+item);
    });
    return input;
  };
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.4.0/lodash.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
  
<div ng-app="myApp" ng-init="foos = [{label:'label 1',id:1},{label:'label 2',id:2},{label:'label 3',id:3}]; selected = []">
  <div ng-repeat="foo in foos">
    <select ng-model="selected[$index]" ng-options="obj.id as obj.label for obj in foos | customFilter:selected:selected[$index]"></select>
  </div>
</div>

相关问题