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
Use ng-init to set default value for 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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With