angular ng-options with preselected value by objec

2019-07-27 01:45发布

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.

4条回答
你好瞎i
2楼-- · 2019-07-27 02:08
<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楼-- · 2019-07-27 02:11

using underscore/lodash use the following lines in controller:

var club =_.where(c.clubs, {name:"club2"});
$scope.c.pilot.clubIdx = club.idx;
查看更多
爷的心禁止访问
4楼-- · 2019-07-27 02:17

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

查看更多
叛逆
5楼-- · 2019-07-27 02:25

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

查看更多
登录 后发表回答