AngularJS – dependent dropdowns: storing one value in model, using other as source of the next dropdown

All we need is an easy explanation of the problem, so here it is.

I have two dependent dropdowns. One shows countries another states.
I would like the first one to save just the country id but use the entire object as source
for the second dropdown. Here’s what I have so far. There could potentially be many of these dropdowns in a same screen so that could complicate things because I would need to duplicate temporary variables(countrySource). Any suggestions?

<select name="country" ng-model="countrySource" ng-options="cntr as cntr.label for cntr in countries" ng-change="country=countrySource.id">
</select>

<select name="state" ng-model="state" ng-options="st.id as st.label for st in countrySource.states">
</select>

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

To keep things simple you can restructure your model as below where the keys act as ids:

$scope.countries = {
    "c1" : {
        label : "Country 1",        
        states:{
            "s1":{
                label:"State 1"             
            },
            "s2" : {
                label:"State 2"             
            }
        }
    },
    "c2" : {
        label:"Country 2",      
        states:{
            "s3":{
                label:"State 3"             
            },
            "s4" : {
                label:"State 4"             
            }
        }
    }
};

HTML

<select ng-model="country" ng-options="countryId as countryDetails.label 
for (countryId, countryDetails) in countries">
</select>

<select name="state" ng-model="state" ng-options="stateId as stateDetails.label 
for (stateId, stateDetails) in countries[country]['states']">
</select>

If by duplicate temporary variables(countrySource), you mean to use the same models for other dropdowns, selecting a country would change the options of all the country and state dropdowns on the page.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply