angular ng-options with preselected value by object id

佐手、 提交于 2019-12-11 11:12:12

问题


Is there a way the following select can have a pre-selected club ?

<select ng-model="c.pilot.clubIdx" ng-options="club.idx as club.name for club in c.clubs track by club.idx">

c.pilot.clubIdx = 2
c.clubs = { {idx: 1, name: "club1"}, {idx: 2, name: "club2"} }

The select-menu should show "club2".

Since the clubs are stored in a db and can be altered, I like to keep them only as references on the pilots.

SOLVED: removing track by solves the problem.


回答1:


in the controller set the ng-model of the select to the value of the option you want selected. Something like : $scope.c.pilot.clubIdx = 2 or $scope.c.pilot.clubIdx = $scope.c.clubs[1].idx




回答2:


<select ng-model="c.pilot.clubIdx" ng-options="club.idx as club.name for club   in c.clubs track by club.idx" ng-selected="(club.idx == 2)?true:false">

add ng-selected like so. It should be preselected




回答3:


using underscore/lodash use the following lines in controller:

var club =_.where(c.clubs, {name:"club2"});
$scope.c.pilot.clubIdx = club.idx;



回答4:


removing the track by clause solves the problem. i dont fully understand why, but who knows. angular doc for ngOptions



来源:https://stackoverflow.com/questions/36643944/angular-ng-options-with-preselected-value-by-object-id

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