-->

angular ng-options with preselected value by objec

2019-07-27 01:23发布

问题:

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