Search code examples
javascriptangularjsangular-uing-options

ng-options where selection of one determines options of the other


I have two dropdowns, and I want the second one to have only the options that are relevant to the selected item in the first. I could do some ng-change function but am trying to get it to work with only code in html, and am close but not quite.

I tried what is found here but it's not quite working. It shows all options instead of none for Level 2 when no selection is made for Level 1, and when a selection is made for Level 1, it only shows the first valid option for Level 2. I'd like, if a is selected for Level 1, it should show b, c, d, e as options for Level 2, and if z is selected, it should show c, d, f, g as options for Level 2.

Here is my code in plnkr:

http://plnkr.co/edit/DuCMjAUKTBiGJNQfhVbd?p=preview

Here is my javascript:

var app = angular.module('myApp', ['ui', 'ui.filters']);
app.controller('myController', function($scope){
  $scope.myFilters = [
    {level1:'a',level2:'b'},
    {level1:'a',level2:'c'},
    {level1:'a',level2:'d'},
    {level1:'a',level2:'e'},
    {level1:'z',level2:'c'},
    {level1:'z',level2:'d'},
    {level1:'z',level2:'f'},
    {level1:'z',level2:'g'},
    ];
});

And here is my html:

<body ng-app="myApp">
 <div ng-controller="myController">
  <form>
  Level 1:
  <select name="level1" ng-model="level1selection" ng-options="myFilter.level1 for myFilter in myFilters | unique:'level1'"></select>
  <br />

  Level 2:
  <select name="level2" ng-model="level2selection" ng-options="myFilter.level2 for myFilter in myFilters | filter:myFilter.level1=level1selection | unique:'level2'"></select>
  </form>
</div>


Solution

  • I figured out a small change that makes my example work, by changing this:

    <select name="level2" ng-model="level2selection" ng-options="myFilter.level2 for myFilter in myFilters | filter:myFilter.level1=level1selection | unique:'level2'"></select>
    

    to this:

    <select name="level2" ng-model="level2selection" ng-options="myFilter.level2 for myFilter in myFilters | filter:myFilter.level1=level1selection.level1 | unique:'level2'"></select>
    

    It seems like the value of the selection was the first entire row in my "table" as opposed to just the displayed value. Not sure if there is a way to set the ng-model to just the displayed value directly?