In this article I will explain with an example, how to use AngularJS ng-options directive to populate Key Value pairs in HTML Select DropDownList.
AngularJS: ng-options Key Value pair example
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-options directive
The ng-options directive accepts an expression which assigns the value from the JSON array to the label and value attribute of HTML Select DropDownList Option.
For example, each item in the JSON array consists of two properties Name and Id. Thus using expression we can notify ng-options what values it must use to populate the HTML Select DropDownList.
ng-options expression
The following expression notifies AngularJS that the Name value will be set to the label attribute and the Id value will be set to the value attribute of the option element of the HTML Select DropDownList.
ng-options="fruit.Name for fruit in Fruits track by fruit.Id"
Now let’s say you just want to bind the label attribute in such case your expression will be as follows.
ng-options="fruit.Name for fruit in Fruits"
In such case, the value attribute will be automatically populated with integer values 1, 2, 3…n.
<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, $window) {
$scope.Fruits = [{
Id: 1,
Name: 'Apple'
}, {
Id: 2,
Name: 'Mango'
}, {
Id: 3,
Name: 'Orange'
}];
});
</script>
<div ng-app="MyApp" ng-controller="MyController">
<select ng-model="ddlFruits" ng-options="fruit.Name for fruit in Fruits track by fruit.Id">
</select>
</div>
</body>
</html>
The following screenshot displays the rendered HTML Select DropDownList populated from JSON array using ng-options directive.
Above screenshot clearly shows how the Id part of the JSON array element has been assigned to the value attribute and the Name part has been assigned to the label attribute.
Demo
Downloads
Download Code