在AngularJS中使用下拉列表时可以利用ng-options实现动态列表,其中的语法为
[modelValue as] labelValue [group by groupValue] for item in array [track by trackValue]
或者
[modelValue as] labelValue [group by groupValue] for (key, value) in object [track by trackValue]
其中,modelValue为实际值,如果没有,则 item 或 value 即为实际值;labelValue为显示值;groupValue为分组参考值;trackValue为比较依据。
<html ng-app="notesApp">
<head>
<title>Notes App</title>
</head>
<body ng-controller="MainCtrl as ctrl">
<div>
<select ng-model="ctrl.selectedCountryId"
ng-options="c.id as c.label group by c.continent for c in ctrl.countries">
</select>
Selected Country ID : {{ctrl.selectedCountryId}}
</div>
<div>
<select ng-model="ctrl.selectedCountry"
ng-options="c.label group by c.continent for c in ctrl.countries track by c.id">
</select>
Selected Country : {{ctrl.selectedCountry}}
</div>
<script src="angular.min.js"></script>
<script>
angular.module('notesApp',[])
.controller('MainCtrl',[function(){
var self = this;
self.countries = [
{label: 'USA', id: 1, continent:'North America'},
{label: 'India', id: 2, continent:'Asia'},
{label: 'China', id: 3, continent:'Asia'},
{label: 'Canada', id: 4, continent:'North America'},
];
self.selectedCountryId = 2;
//使用self.countries[1]为self.selectedCountry赋值,它们的引用一致,所以不需要使用track by语法指明其他比较依据
//self.selectedCountry = self.countries[1];
//因为此处为selectedCountry赋值使用的是一个新的对象,虽然它和self.countries[1]
//内容一致,但引用不一致,所以在第二个下拉列表初始化时,并没有与之对应的值显示
//为了修正这一点,可以在ng-options中加入track by c.id指明比较时使用id值,而不是引用。
self.selectedCountry = {label: 'India', id: 2, continent:'Asia'};
}]);
</script>
</body>
</html>