<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>
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.
Here's an alternate method for initializing a drop down menu using AngularJS.
(working example on JS Fiddle: http://jsfiddle.net/galeroy/100ho18L/1/)
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>
<body ng-app="" ng-controller="myController">
<select
ng-model="carSelection"
ng-options = "x.make for x in cars">
</select>
<script>
function myController($scope) {
$scope.cars = [
{"make": "Nissan", "model": "Sentra"},
{"make": "Honda", "model": "Prelude"},
{"make": "Toyota", "model": "Prius"}
]
$scope.carSelection = $scope.cars[1]; // this line initializes the drop down menu
}
</script>
</body>
As @camus already mentioned in a comment, you need to set the model to a valid "label" value (or reference), not an index value. This is a bit odd since you can see an index value being used in the HTML.
Angular sets the value attributes in the HTML as follows:
When an item is selected, Angular looks up the correct entry in the array/object based on the index or property name.