根据其他下拉列表angularjs ng-option筛选下拉列表

时间:2016-06-09 10:25:29

标签: angularjs json angularjs-filter angularjs-ng-options

我正在尝试使用相同的JSON对象实现级联下拉选项以填充下拉列表。

CODE

var app = angular.module('App', []);

app.controller('MainCtrl', function($scope) {
  $scope.fruit1 = {};
  $scope.fruit2 = {};
  $scope.fruits = [{
      "id": "1",
      "value": "Apple"
    },
    {
      "id": "2",
      "value": "Banana"
    },
    {
      "id": "3",
      "value": "Cherry"
    },
    {
      "id": "4",
      "value": "Fig"
    },
    {
      "id": "5",
      "value": "Grapes"
    }
  ];
  $scope.fruit1.id = "1";
  $scope.fruit2.id = "2";
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="App">
  <div ng-controller="MainCtrl">
    1st list
    <select ng-model="fruit1.id" ng-options="x.id as x.value for x in fruits">
        </select>
    <br/> 2nd list
    <select ng-model="fruit2.id" ng-options="x.id as x.value for x in fruits">
        </select>
  </div>
</div>

现在,当我从第一个下拉列表中选择“Apple”时,应从第二个下拉列表中删除。我无法弄清楚如何实现这一点。

以下是Fiddle

2 个答案:

答案 0 :(得分:1)

使用过滤器和ng-select后发现了一个非常简单的解决方案。

只需在ng-option中添加过滤器。

<select ng-model="fruit1.id" ng-options="x.id as x.value for x in fruits | filter: {id: '!' + fruit2.id}">
</select>

<select ng-model="fruit2.id" ng-options="x.id as x.value for x in fruits | filter: {id: '!' + fruit1.id}">
</select>

它完成了所有的魔力。 这个答案让我的问题变得如此愚蠢。

UPDATED FIDDLE

答案 1 :(得分:0)

在下拉列表中使用ng-change。 像:

<select ng-model="fruit1.id" ng-options="x.id as x.value for x in fruits" ng-change = "removeFromList(fruit1.id)">
    </select>

并在您的控制器中:

$scope.removeFromList(val){
//remove val from list
}