[html]
<html ng-app="app">
<body>
<div ng-controller="Test">
<p>selected item is : {{selectedItem}}</p>
<select ng-model="selectedItem">
<option ng-repeat="item in items" value="{{item}}">{{item}}</option>
</select>
</div>
</body>
</html>
[/html]
AngularJS code:
[javascript]
var app = angular.module('app',[]);
app.controller('Test',function($scope){
$scope.items = ['one','two','three','four']
});[/javascript]
The above code doesn't change when array items has only strings. But, it should be not used when array items has objects. In this case, ng-options is used instead of ng-repeat because element option can hold only string type as its value.So, the above code is written using ng-options like below.
[javascript]
$scope.items = [{name: 'one', age: 30 },{ name: 'two', age: 27 },{ name: 'three', age: 50 }];
[/javascript]
And the new HTML code looks like below:
[html]
<html ng-app="app">
<body>
<div ng-controller="Test">
<p>selected item is : {{selectedItem}}</p>
<p> age of selected item is : {{selectedItem.age}} </p>
<select ng-model="selectedItem" ng-options="item.name for item in items">
</select>
</div>
</body>
</html>
[/html]
In the above example, the initial element of dropdown is empty as "selectedItem" will not have any default value and is undefined. Since there’s no option is selected by default, AngularJS creates a new option tag and select it as default. To fix the issue, just set the "selectedItem" to the first object in the items array.
$scope.selectedItem = $scope.items[0];