ng repeat list dropdown筛选另一个列表下拉列表

时间:2016-06-10 21:32:58

标签: javascript angularjs

我有两个下拉列表,如下所示:

HTML

<div class="col-md-3">
    <select class="form-control"  ng-model="select1">
        <option value="" selected disabled>Select First</option>
        <option  ng-repeat="item in items" value="{{item.name}}">{{item.name}}</option>
    </select>
</div>
<div class="col-md-2">
    <select class="form-control"  ng-model="select2">
        <option value="" selected disabled>Select Second</option>
        <option ng-repeat="item in items|filter:itemFilter" value="{{item.stuff}}">{{item.stuff}}</option>
    </select>
</div>

我的items列表如下:

[
  {name:"foo1", stuff:["bar1","bar2","bar3"]},
  {name:"foo2", stuff:["bar4","bar5","bar6"]},
  {name:"foo3", stuff:["bar7","bar8","bar9"]}
]

控制器

 $scope.itemFilter = function (item) {
         return item.name == $scope.select1;
};

目标

当我从第一个下拉列表中选择foo1时,第二个下拉列表应包含3个选项bar1bar2bar3

当前

当我从第一个下拉列表中选择foo1时,第二个下拉列表包含一个选项["bar1","bar2","bar3"]

1 个答案:

答案 0 :(得分:2)

一种方法是使用方法进行过滤,并在第一个下拉菜单的ngChange上调用该过滤方法。

<select class="form-control"  ng-model="select1" ng-change="filterItems()">

以下是过滤方法的定义

$scope.filterItems = function() {
  var index = 0;
  for (var i = 0; i < $scope.items.length; i++) {
    if ($scope.items[i].name == $scope.select1) {
      index = i;
      break;
    }
  }
  $scope.filteredItems = $scope.items[index].stuff;
};

将第二个下拉列表绑定到已过滤的列表

<select class="form-control"  ng-model="select2">
    <option value="" selected disabled>Select Second</option>
    <option ng-repeat="item in filteredItems">{{item}}</option>
</select>

Here is a fully working Plunkr