Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set default value in ng-options

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

like image 874
mpsbhat Avatar asked Nov 30 '15 07:11

mpsbhat


People also ask

How do I set default Ng-options?

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

How do I filter with Ng-options?

In AngularJS when you are using ng-options, you can filter out the options by calling a custom function you have in the controller. Let's say you have following set of employees and when you display all these employees inside HTML select using ng-options, you can see all the employees in a dropdown.

What is the difference between ng-repeat and Ng-options?

ng-repeat creates a new scope for each iteration so will not perform as well as ng-options. For small lists, it will not matter, but larger lists should use ng-options. Apart from that, It provides lot of flexibility in specifying iterator and offers performance benefits over ng-repeat.

How do ng-options work?

The ng-options directive fills a <select> element with <options>. The ng-options directive uses an array to fill the dropdown list. In many cases it would be easier to use the ng-repeat directive, but you have more flexibility when using the ng-options directive.


1 Answers

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>
like image 62
Upalr Avatar answered Sep 29 '22 10:09

Upalr