var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $timeout) {
$scope.loading = true;
$timeout(function() {
populateDBObject({
id: 3,
text: 'Three'
});
$scope.loading = false;
}, 1000);
$scope.options = [{
groupName: 'First',
display: 'First - One',
value: {
id: 1,
text: 'One'
}
}, {
groupName: 'First',
display: 'First - Two',
value: {
id: 2,
text: 'Two'
}
}, {
groupName: 'Second',
display: 'Second - Third',
value: {
id: 3,
text: 'Third'
}
}, {
groupName: 'Second',
display: 'Second - Four',
value: {
id: 4,
text: 'Four'
}
}];
$scope.simulateUpdate = function ($event) {
populateDBObject($scope.options[Math.floor(Math.random() * 4)].value);
if ($event) $event.preventDefault();
};
function populateDBObject(value) {
$scope.dbObject = angular.extend({}, {
id: 'ffffffffffffffffffff',
name: 'some record',
desc: 'this is some dummy record'
}, {
value: value
});
}
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<link data-require="bootstrap-css@*" data-semver="3.2.0" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
<script data-require="angular.js@1.3.0-rc.4" data-semver="1.3.0-rc.4" src="https://code.angularjs.org/1.3.0-rc.4/angular.js"></script>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<div class="container">
<h1>Select as and track by example</h1>
<p>The following select should have "Second - Third" selected, once the
database object on the scope is "loaded", even though the original bound
ng-model value is <code>{{:: dbObject.value | json }}</code>.
</p>
<p>
<select ng-model="dbObject.value"
ng-options="opt.value as opt.display group by opt.groupName for opt in options track by (opt.id || opt.value.id)">
</select>
<span class="loading" ng-if="loading">Loading...</span>
</p>
<p>This is accomplished by using a <code>track by</code>
expression that utilises <code>||</code>
to work for both the model value and the option object in the array (track by = <code>opt.id || opt.value.id</code>
).
</p>
<p>You can <a href="#" ng-click="simulateUpdate($event)">simulate a random DB update</a> too.
<p>If you try changing the version of AngularJS in <code>index.html</code>
used to 1.3.0-rc.5, it will stop working.</p>
</div>
</body>
</html>
/* Put your css in here */
.container {
margin: 20px 0 20px 0;
}