This isn't specifically related to angularjs, but rather JavaScript. I borrowed a filter from the chat example of angularjs and firebase, and this is how it appears.
angular.module('myApp')
.filter('reverse', function () {
function toArray(list) {
var k, out = [];
if( list ) {
if( angular.isArray(list) ) {
out = list;
}
else if( typeof(list) === 'object' ) {
for (k in list) {
if (list.hasOwnProperty(k)) {
out.push(list[k]);
}
}
}
}
return out;
}
return function(items) {
return toArray(items).slice().reverse();
};
});
The issue with this code is that it removes an essential part of the object - its key. I rely on this key to query for a single object.
In my template:
<div ng-repeat="(id, post) in posts | orderByPriority | reverse">
<a href="posts/{{post.id}}">{{post.title}}</a>
</div>
I can't use the id
in (id, post)
because it's just the index of the reversed
array (0,1,2,3...).
I attempted to add this into the reverse filter, but couldn't get it to work.
for (k in list) {
if (list.hasOwnProperty(k)) {
list[k].id = k; // this is the line I added.
out.push(list[k]);
}
}