How to set preselected value in ng-option?

微笑、不失礼 提交于 2021-02-08 10:17:23

问题


I have id from the city that is supposed to be selected in dropdown list, but I can`t manage to preselect it. Should I select it from directive or is there any other way?

<select  ng-model="cityId" ng-options="city.name for city in cities"></select>

回答1:


Edit your ng-options to this:

city.id as city.name for city in cities

if you fetch the cities and don't know the ID's you could say in your javascript success function (which returns the cities):

$scope.cityId = the_cities[0].ID

to set the first as selected Else you could just say:

$scope.cityId = 1; //or anything that exists



回答2:


You would need to use select as part for that, provided id is respective property on city object you would do:

ng-options="city.id as city.name for city in cities"

Otherwise you need to provide same object reference (of city object in the array) as the ng-model (if not using track-by).

When using track-by you would do:

ng-options="city.name for city in cities track by city.id"

and set the model as:

$scope.cityId = {id:'CITY1'};

When track by is used you do not need to worry about object references and it will actually have the value property of options reflecting exact id (unlike select as which keeps an internal map with index). This is helpful when doing form posts. But you should be careful not to mix it with select as since both are meant for different purposes and the implementation conflicts each other.



来源:https://stackoverflow.com/questions/30510261/how-to-set-preselected-value-in-ng-option

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!