In this article I will explain with an example, how to use populate HTML Select DropDownList with selected option using AngularJS.
Populating HTML DropDownList Select with selected option
The below HTML Markup consists of an HTML DIV to which ng-app and ng-controller AngularJS directives have been assigned.
The HTML DIV consists of an HTML Select DropDownList which will be populated from JSON array using ng-options directive.
A JSON array has been created inside the controller and assigned to the Fruits variable.
ng-repeat directive
The ng-repeat directive as the name suggests repeats the element based on the length of the collection.
The option element has been assign ng-repeat directive to iterate to all items of the Fruits array.
The Id property is assigned to the value attribute and the Name property is set as inner HTML for the option element.
ng-selected directive
In order to set an option as selected, you will need to use the ng-selected directive and assign it a Boolean expression. In the following example an option must be set as selected if the Selected property is true.
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope) {
$scope.Fruits = [{
Id: 1,
Name: 'Apple',
Selected: false
}, {
Id: 2,
Name: 'Mango',
Selected: true
}, {
Id: 3,
Name: 'Orange',
Selected: false
}];
});
</script>
<div ng-app="MyApp" ng-controller="MyController">
<select>
<option value = "0" label = "Please Select"></option>
<option ng-repeat="fruit in Fruits" value="{{fruit.Id}}"
ng-selected="{{ fruit.Selected == true }}">
{{fruit.Name}}
</option>
</select>
</div>
</body>
</html>
The following screenshot displays the rendered HTML Select DropDownList with selected option populated using ng-repeat directive.
Demo
Downloads