AngularJS依赖的下拉列表:在模型中存储一个值,使用其他值作为下一个下拉列表的源

vla*_*ija 4 javascript angularjs

我有两个依赖的下拉菜单.一个显示另一个国家.我想第一个只保存国家ID但使用整个对象作为第二个下拉列表的源.这是我到目前为止所拥有的.在同一个屏幕上可能存在许多这些下拉列表,因此可能会使事情变得复杂,因为我需要复制临时变量(countrySource).有什么建议?

<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>
Run Code Online (Sandbox Code Playgroud)

Alw*_*ner 12

为了简单起见,您可以重新构建模型,如下所示,其中键作为ID:

$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"             
            }
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

如果是duplicate temporary variables(countrySource),您的意思是将相同的模型用于其他下拉列表,则选择一个国家/地区将更改页面上所有countrystate下拉列表的选项.