Skip to content

Instantly share code, notes, and snippets.

@mritzco
Last active January 28, 2017 15:13
Show Gist options
  • Save mritzco/8840960 to your computer and use it in GitHub Desktop.
Save mritzco/8840960 to your computer and use it in GitHub Desktop.
AngularJS, setting ng-options for different data sources
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.items = [
{ID: '000001', Title: 'Chicago'},
{ID: '000002', Title: 'New York'},
{ID: '000003', Title: 'Washington'}
];
$scope.items2 =
{ '000001' : { name: 'Chicago'},
'000002' : { name: 'New York'},
'000003' : { name: 'Washington'}}
;
$scope.items3 =
{ '000001' : 'Chicago',
'000002' : 'New York',
'000003' : 'Washington'}
;
$scope.items4 =
{'Chicago': { 'population' :5000, 'shortcode':'CH'},
'New York': { 'population' :5000, 'shortcode':'CH'},
'Washington': { 'population' :5000, 'shortcode':'CH'}}
;
});

Angular ng-options

Examples of setting ng-options with different data-sources.

All samples return the selected key as string.

Setting values from DB

Stored data usually includes the key only and comes from a different source. Just set the model to the stored value and the select control will show properly.

$scope.model3 = dbValue;

See it working

http://plnkr.co/edit/fGq2PM?p=info

Check out the gist

https://gist.github.com/mritzco/8840960/

See it on gist.io

http://gist.io/8840960

<!doctype html>
<html ng-app="plunker">
<head>
<meta charset="utf-8">
<title>AngularJS Plunker</title>
<link rel="stylesheet" href="style.css">
<script>
document.write("<base href=\"" + document.location + "\" />");
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<h1>Multiple ways of setting ng-options</h1>
<h3>Options from an array of objects</h3>
<select ng-model="model" ng-options="item.ID as item.Title for item in items"></select>
<p>Selected: {{model}}</p>
<h3>Options from a single object (keys:values,)</h3>
<select ng-model="model2" ng-options="k as v.name for (k, v) in items2"></select>
<p>Selected: {{model2}}</p>
<h3>Options from an object with keys</h3>
<select ng-model="model3" ng-options="k as v for (k, v) in items3"></select>
<p>Selected: {{model3}}</p>
<h3>Options from an object with keys</h3>
<select ng-model="model4" ng-options="k as k for (k, v) in items4"></select>
<p>Selected: {{model4}}</p>
* Based on original sample at: http://plnkr.co/edit/fGq2PM?p=preview
** Plunkr: http://plnkr.co/edit/fGq2PM?p=preview
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment