How to set default value in ng-options

mpsbhat picture mpsbhat · Nov 30, 2015 · Viewed 53.3k times · Source

I can set a dropdown list with default value in angularjs as,

 <select name="repeatSelect" id="repeatSelect" ng-model="repeatSelect" ng-init=" repeatSelect = data[0].id">
    <option ng-repeat="option in data" value="{{option.id}}">{{option.name}}</option>
 </select>

How can I achieve the same using ng-options? I treid with,

 <select name="repeatSelect" 
   id="repeatSelect" 
   ng-model="repeatSelect"
   ng-init=" repeatSelect = option.id"  
   ng-options="option.name for option in data track by option.id">
</select>

But no use. Sample fiddle is here

Answer

Upal Roy picture Upal Roy · Nov 30, 2015

Use ng-init to set default value for ng-options.

Here is the: demo

<select name="repeatSelect" 
   id="repeatSelect" 
   ng-model="repeatSelect"
   ng-init=" repeatSelect = data[0].id"  
   ng-options="option.id as option.name for option in data">          
</select>