Thursday 16 June 2016

Angular.js ng-repeat Over an Object

<html ng-app="notesApp">
<head><title>Notes App</title></head>
<body ng-controller="MainCtrl as ctrl">
<div ng-repeat="(author, note) in ctrl.notes">
<span class="label"> {{note.label}}</span>
<span class="author" ng-bind="author"></span>
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.js">
</script>
<script type="text/javascript">
angular.module('notesApp', [])
.controller('MainCtrl', [function() {
var self = this;
self.notes = {
shyam: {
id: 1,
label: 'First Note',
done: false
},
Misko: {
id: 3,
label: 'Finished Third Note',
done: true
},
brad: {
id: 2,
label: 'Second Note',
done: false
}
};
}]);
</script>
</body>
</html>

OUTPUT


Finished Third Note Misko
Second Note brad
First Note shyam

Explanation:
In this example, we have intentionally capitalized Misko while leaving brad and shyam
lowercase. When we use the ng-repeat directive over an object instead of an array, the
keys of the object will be sorted in a case-sensitive, alphabetic order. That is, uppercase
first, and then sorted by alphabet. So in this case, the items would be shown in the HTML
in the following order: Misko, brad, shyam.

No comments:

Post a Comment