AngularJS - dependent drop-down lists: saving one value in the model, using another as the source of the next drop-down list

I have two dependent dropdowns. One shows countries to other states. I would like the first to save only the country identifier, but use the entire object as a source for the second drop-down list. Here is what I still have. Perhaps many of these drop-down lists can be displayed on one screen, which can complicate the situation because I will 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> 
+4
source share
1 answer

To keep things simple, you can rebuild your model, as shown below, where the keys act as identifiers:

 $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 in the duplicate temporary variables(countrySource) you want to use the same models for other drop-down menus, choosing a country will change the settings for all the country and state drop-down lists on the page.

+12
source

Source: https://habr.com/ru/post/1500869/


All Articles