Select directive not selecting option when options are loaded asynchronously

旧街凉风 提交于 2019-12-24 11:22:12

问题


I have a <select> directive whose options are loaded asynchronously. The variable that the ng-model attribute points to exists prior to the options being loaded. However, after the options are loaded the correct option is not selected. Instead, the select becomes blank. I've created a plunk to demonstrate this behaviour: http://plnkr.co/edit/KNunC6.


回答1:


https://github.com/angular/angular.js/issues/9714#ref-pullrequest-53337829

seems like this is an angular core bug. you'd be more successful using ng-repeat and ng-checked I guess.




回答2:


I think this fixes your issue. Here's a plunker. The problem was that you were initializing the ngModel before the promise was finished. The ngModel needs to be initialized after the list gets populated so angular can figure out which option is selected. Also, the ngOptions is tricky sometimes because angular assigns a unique id to every option and ignores the value attribute. I had this issue a couple of times also, nasty one!




回答3:


There is a problem when the value part of the option has the same value as the label part.

In your case, value == id == 'Canada' and label == name == 'Canada' as well. If you change one of them to anything else, it will work. I am not sure why it is an issue, but just change and it will be ok.

Example: change the name from 'Canada' to 'Canada ':

[
    { id: 'Canada', name: 'Canada ' }, 
    { id: 'US', name: 'United States of America' }
]


来源:https://stackoverflow.com/questions/27789006/select-directive-not-selecting-option-when-options-are-loaded-asynchronously

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