场景:
Select初始化之后,选中select的某个选项
通过AngularJS更新select的选项
错误写法:
HTML(使用ng-repeat)
<div ng-app="TestApp">
<div ng-controller="TestAppCtrl">
<label>options变化之后会出错:</label>
<select ng-model="selectedSite">
<option value="" >---请选择---</option>
<option ng-repeat="site in sites" value="{{site.url}}">{{site.name}}</option>
</select>
<input type="button" ng-click="reload()" value="更新">
</div>
<div>
var testApp = angular.module('TestApp', []);
testApp.controller('TestAppCtrl', ['$scope',
function($scope) {
var sites=[{"url":"http://www.baidu.com","name":"百度"},
{"url":"http://www.google.com","name":"谷歌"},
{"url":"http://www.yahoo.com","name":"雅虎"},
]
var sites2=[{"url":"http://www.gmail.com","name":"GMAIL"},
{"url":"http://www.abc.com","name":"ABC"},
{"url":"http://www.xyz.com","name":"XYZ"},
] var Init = function(){
$scope.sites=sites;
} var Reload = function(){
$scope.sites=sites2;
}
//加载页面之后初始化
Init();
//注册更新按钮的点击事件,点击之后更新select的option列表
$scope.reload=Reload;
}]
);
按照场景描述的步骤操作之后,下拉菜单变成如下所示(多出了一个option,option的value和步骤一所选的选项有关,我第一步选了“百度”):
正确写法:
HTML(使用ng-options), javascript不变
<div ng-app="TestApp">
<div ng-controller="CorrectedAppCtrl">
<label>正确写法:</label>
<select ng-model="selectedSite" ng-options="site as site.name for site in sites track by site.url">
<option value="" >---请选择---</option>
</select>
<input type="button" ng-click="reload()" value="更新">
</div>
<div>
官方文档说这两种方式都可以实现下拉列表,也说了一些ngOptions优于ngRepeat的点。但是没看到说会引起这个原因,root cause还是不知道。总之,以后用ngOptions吧。
https://docs.angularjs.org/api/ng/directive/ngOptions