Reputation: 1158
My goal here is to generate a select list that has the option values set to one of my objects properties. When adding the track by binding option to the ng-options directive an unknown option element is created and it is the only option that ever shows selected. This behavior is in angular v1.3 (which is the version I'm using). In v1.4 it still creates the unknown item but will change the display to show a different selected item. In neither case does it set the initial state of the dropdown to correspond to the model value.
ng-options Track By example v1.3
<body>
<script>
angular.module('plunker', [])
.controller("MyCntrl", function($scope) {
$scope.myColor = "rd"; // red
$scope.colors = [
{name:'black', code:'bk'},
{name:'white', code:'wh'},
{name:'red', code:'rd'},
{name:'blue', code:'bl'},
{name:'yellow', code:'yl'}
];
});
</script>
<div ng-controller="MyCntrl">
<select ng-model="myColor" ng-options="color.code as color.name for color in colors track by color.code"></select><br>
<hr/>
<span>Currently selected: {{myColor}}</span>
</div>
</body>
In v1.4 it still does not set the initial state but upon select a new value it will change the display. I find it strange that this doesn't work and that it's not been an issue.
In case you're wondering, we want this so that the the option values are known codes that our test automation can key on and the only thing we want the model value to be is the code. Seems like a a fairly standard thing to do.
Upvotes: 1
Views: 826
Reputation: 1690
You need to set the value to be the entire object in your controller.
$scope.myColor ={name:'red', code:'rd'};
Then it will properly select.
Upvotes: 0