Reputation: 335
I'm displaying a select dialog like this:
<select ng-model="myFormData.theList" ng-options="list.listName for list in myList track by list.listValue">
which outputs something like this:
<option value="abc">list name 1</option>
<option value="def">list name 2</option>
<option value="ghi">list name 3</option>
<option value="jkl">list name 4</option>
and I know I can have a default selection via the array INDEX by adding a ng-init to my select like this:
<select ng-model="myFormData.theList" ng-init="myFormData.theList = myList[1]" ng-options="list.listName for list in myList track by list.listValue">
how do I set the default selection by list.listValue?
Upvotes: 1
Views: 14037
Reputation: 41
Another option besides setting a function is to format the searched value from ng-init as a hash with the same attribute used by track by:
<select
ng-init="myFormData.theList = { listValue: 'ghi'}"
ng-model="myFormData.theList"
ng-options="list.listName for list in myList track by list.listValue">
</select>
See the: Plunker sample
Upvotes: 2
Reputation: 54504
<select ng-model="myFormData.theList"
ng-init="myFormData.theList = myList[1].listValue"
ng-options="list.listValue as list.listName for list in myList">
Upvotes: 0
Reputation: 3820
Set a function on your scope that takes the value and returns the index:
scope.getIndexFromValue = function(value) {
for(var i=0; i<scope.list.length; i++) {
if(scope.list[i].listValue === value)
return i;
}
};
then call it from the ng-init markup:
<select ng-model="myFormData.theList" ng-init="myFormData.theList = myList[getIndexFromValue('abc')]" ng-options="list.listName for list in myList track by list.listValue">
Upvotes: 5
Reputation: 2865
As per Angular documentation: "ngModel compares by reference, not value. This is important when binding to an array of objects."
The only way I can think to do this would be to iterate through your array and set myFormData.theList equal to the actual object that matches the listValue in your controller when it initializes or when you grab your data via a service call.
Upvotes: 0