Binding HTML select boxes to the scope and selecting a value as default in AngularJS can be a little confusing, so I thought I’d write a quick, simple tutorial on it.
First we’ll need some data to work with so we’ll build a simple array of month objects in the controller:
$scope.months = [
{
'id' :1,
'name' : 'January'
},
{
'id' :2,
'name' : 'February'
},
{
'id' :3,
'name' : 'March'
},
{
'id' :4,
'name' : 'April'
},
{
'id' :5,
'name' : 'May'
},
{
'id' :6,
'name' : 'June'
},
{
'id' :7,
'name' : 'July'
},
{
'id' :8,
'name' : 'August'
},
{
'id' :9,
'name' : 'September'
},
{
'id' :10,
'name' : 'October'
},
{
'id' :11,
'name' : 'November'
},
{
'id' :12,
'name' : 'December'
}
]
Now we have some data, we can use this to create a select box within our angular template. We do this by iterating over the array using ng-options. We use ng-options rather than ng-repeat as it allows us to set different values for the option text and option value:
<select ng-model="month" ng-options="month.id as month.name for month in months"></select>
This will show the populated select box as below, but without any value selected.
The ng-options expression looks very confusing, but it’s actually quite simple. This is what it means:
ng-options=”optionValue as optionText for obJectIndataArray in dataArray”
For example, for the first object in $scope.months, the option will output as:
<select ng-model="month">
<option value="1">January</option>
</select>
Now we’ve got our select box and options showing we just need to set a default value. We can do this using the ng-init directive on the <select> tag.
We have already bound the select box to the scope using ng-model=”month”. Now we just need to use ng-init to give $scope.month a value:
<select ng-model="month" ng-options="month.id as month.name for month in months" ng-init="month = 2"></select>
This will set the option with a value of 2 as the default. In this case February as you can see below.