Search code examples
angularjsjsonangularjs-filterangularjs-ng-options

Filter Dropdown List depending on other dropdown list angularjs ng-option


I'm trying implement cascading drop down options using same JSON object to populate both the dropdown.

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>

Now when I select "Apple" from 1st dropdown that should get removed from 2nd dropdown. I cant figure out how to implement this.

Here is the Fiddle


Solution

  • After playing with filter and ng-select found a very simple solution.

    Just add Filter in 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>
    

    It does all the magic. This Answer makes my question so stupid.

    UPDATED FIDDLE