Simo Mafuxwana
Simo Mafuxwana

Reputation: 3762

AnglularJS: Populate second select-dropdown based on choice of first select-dropdown

I have a set of select-dropdown menus, I am trying to populate second select-dropdown based on choice of first select-dropdown in angularJS. I don't know how to actually start with this.

I have all model ready but am struggling with the dynamic population.

Select 1:

    <select ng-model="selectedSource" ng-options="source.name for source in sourceList">
       <option value="">-- Select item --</option>
    </select>

$scope.sourceList= [
    {
       "name":"Person",
       "has": ["a","b","c"]
    },
    {
       "name":"Car",
       "has": ["1","2","3"]
    }
];

What am trying to achieve:

When sourceList.name is Person populate 2nd select-dropdown with targerSet1

$scope.targerSet1= [
   {
      "name":"King Julien"
   }
];

When sourceList.name is Car populate 2nd select-dropdown with targerSet2

$scope.targerSet2= [
   {
      "name":"RoyalMobile"
   }
];

Upvotes: 5

Views: 8147

Answers (1)

lort
lort

Reputation: 1457

You can just use binded variable from first select in ng-options of second one:

Selects

<select ng-model="selectedSource" ng-options="source.name for source in sourceList">
    <option value="">-- Select item --</option>
</select>

<select ng-model="selectedItem" ng-options="item.name for item in selectedSource.suboptions">
    <option value="">-- Select item --</option>
</select>

Controller

$scope.sourceList = [
    {
       name: "Person",
       suboptions: [
           { name: "King Julien" }
       ]
    },
    {
       name: "Car",
       suboptions: [
           { name: "RoyalMobile" }
       ]
    }
];

Upvotes: 7

Related Questions