How to have a default option in Angular.js select box

iConnor picture iConnor · Aug 12, 2013 · Viewed 503.9k times · Source

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>

Answer

zs2020 picture zs2020 · Aug 12, 2013

You can simply use ng-init like this

<select ng-init="somethingHere = options[0]" 
        ng-model="somethingHere" 
        ng-options="option.name for option in options">
</select>