<select ng-model="team.captain" ng-options="player.name for player in team.players"></select>
This correctly creates a select list to choose the team captain. However, by default a blank option is selected. How can we preselect the first player from the list instead?
<select ng-model="team.captain" ng-options="player.name for player in team.players" class="ng-pristine ng-valid"> <option value="0">John</option> <option value="1">Bobby</option> </select>
I tried adding ng-init="team.captain='0'"
but that didn't help.
Update Apparently this happens because
a value referenced by ng-model doesn't exist in a set of options passed to ng-options.
Source: Why does AngularJS include an empty option in select?
However, the question still remains why using ng-init doesn't work?
<select ng-init="team.captain='0'" ng-model="team.captain" ng-options="player.name for player in team.players"></select>
The select directive is used together with ngModel to provide data-binding between the scope and the <select> control (including setting default values). It also handles dynamic <option> elements, which can be added using the ngRepeat or ngOptions directives.
In order to pre-select an item on the drop down list you can do so prior to the page being rendered by adding a selected="selected" attribute inside the required option.
The ng-selected Directive in AngularJS is used to specify the selected attribute of an HTML element. It can be used to select the default value specified on an HTML element. If the expression inside the ng-selected directive returns true then the selected option value will be displayed otherwise not displayed.
Here's what worked:
<select ng-init="team.captain=team.players[0]" ng-model="team.captain" ng-options="player.name for player in team.players"></select>
And what didn't work:
ng-init="team.captain='0'" ng-init="team.captain='John'"
My guess is that Angular goes beyond simple comparison of values or labels. It probably compares object references.
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