用于选择和Ng选项的AngularJS指令模板

时间:2013-11-18 19:40:44

标签: angularjs angularjs-directive

我在尝试将以下html代码段转换为一对指令中的等效模板时遇到了麻烦。

<select ng-model="address.country" ng-change="address.division=null"
        ng-options="countryId as countryDetails.label for (countryId, countryDetails) in countries"></select>
<select ng-model="address.province" 
        ng-options="divisionId as divisionDetails.label for (divisionId, divisionDetails) in countries[address.country]['divisions']"></select>

countries变量具有以下结构:

countries = {
    "": {
        label: "",
        divisions: {
            "": {label: ""}
        }
    },
    "Canada": {
        label: "Canada",
        divisions: {
            "": {label: ""},
            "Alberta": {label: "Alberta"},
            "British Columbia": {label: "British Columbia"},
            etc . . .
        }
    },
    "United States": {
        label: "United States",
        divisions: {
            "": {label: ""},
            "Alabama": {label: "Alabama"},
            "Alaska": {label: "Alaska"},
            etc . . .
        }
};

在我的指令中使用以下作为模板创建了一个下拉列表,但它没有值。国家/地区列表在javascript文件中定义,其中指令是全局变量,国家/地区在指令范围内定义为匹配属性的字符串值。

template: '<select ng-options="divisionId as divisionDetails.label for (divisionId, divisionDetails) in countries[{{country}}]['divisions']" ></select>',

1 个答案:

答案 0 :(得分:1)

我会使用ng-repeat键+值。

<强> HTML

<select ng-model="selectedmodel">
    <option ng-repeat="(key,val) in countries">{{val.label}}</option>
</select>  

<select >
    <option ng-repeat="(key,val) in countries[selectedmodel].divisions">{{val.label}}</option>
</select>

<强> JS

$scope.countries = {
    "Hartabarta": {
        label: "Hartabarta",
        divisions: {
            "": {label: ""}
        }
    },
    "Canada": {
        label: "Canada",
        divisions: {
            "": {label: ""},
            "Alberta": {label: "Alberta"},
            "British Columbia": {label: "British Columbia"}           
        }
    },
    "United States": {
        label: "United States",
        divisions: {
            "": {label: ""},
            "Alabama": {label: "Alabama"},
            "Alaska": {label: "Alaska"}            
        }
    }
};

$scope.selectedmodel = 'Canada';

演示 Fiddle

希望这就是你想要的。