I have searched Google and can't find anything on this.
I have this code.
<select ng-model="somethingHere"
ng-options="option.value as option.name for option in options"
></select>
With some data like this
options = [{
name: 'Something Cool',
value: 'something-cool-value'
}, {
name: 'Something Else',
value: 'something-else-value'
}];
And the output is something like this.
<select ng-model="somethingHere"
ng-options="option.value as option.name for option in options"
class="ng-pristine ng-valid">
<option value="?" selected="selected"></option>
<option value="0">Something Cool</option>
<option value="1">Something Else</option>
</select>
How is it possible to set the first option in the data as the default value so you would get a result like this.
<select ng-model="somethingHere" ....>
<option value="0" selected="selected">Something Cool</option>
<option value="1">Something Else</option>
</select>
Try this:
HTML
Javascript
Plunker here.
If you really want to set the value that will be bound to the model, then change the
ng-options
attribute toand the Javascript to
Another Plunker here considering the above.
Depending on how many options you have, you could put your values in an array and auto-populate your options like this
In response to Ben Lesh's answer, there should be this line
instead of
That is,
If you are using
ng-options
to render you drop down thanoption
having same value as of ng-modal is default selected. Consider the example:So option having same value of
list.key
andselectedItem
, is default selected.I think, after the inclusion of 'track by', you can use it in ng-options to get what you wanted, like the following
This way of doing it is better because when you want to replace the list of strings with list of objects you will just change this to
where somethingHere is an object with the properties name and id, of course. Please note, 'as' is not used in this way of expressing the ng-options, because it will only set the value and you will not be able to change it when you are using track by
I would set the model in the controller. Then the select will default to that value. Ex: html:
Angular controller (using resource):