Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a preselection for a select list generated by AngularJS?

<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> 
like image 204
randomguy Avatar asked Jan 12 '13 20:01

randomguy


People also ask

Can I use ngModel for 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.

How to pre select dropdown value in JavaScript?

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.

What is Ng selected in AngularJS?

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.


1 Answers

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.

like image 61
randomguy Avatar answered Sep 20 '22 14:09

randomguy