12
votes

So I have an array that I'm using ng-repeat to render out but I want to reverse this list. Previously I have used a filter which i got from this answer: angular ng-repeat in reverse

But now I get an error: "TypeError: Object # has no method 'slice' at Scope." I'm not sure if this is because of a new version of AngularJS or I'm missing something.

This is my filter code:

.filter('reverse', function () {
return function(items) {
    return items.slice().reverse();
};

This is the code from my view from inside the div:

data-ng-repeat='feed in feeds | reverse'
7
looks like feeds is not an array... - michael
I'm using firebase to bind a local $scope.feeds object with the backend. - ph3bell
so item may be undefined. please check this und return items without modifiying it or return nothing - michael

7 Answers

18
votes

To make the array render in reverse and ordered by 'id', this should work:

data-ng-repeat="feed in feeds | orderBy:'id':true"

Let me know if that works for you.

For your reference: http://jsfiddle.net/byizzy/pgPVU/3/

12
votes

This is a bit tricky, but for all the people interested in reversing an array without creating new predicate functions and/or modifying the array etc...

ng-repeat="feed in feeds | orderBy:'':true"

or

ng-repeat="feed in feeds | orderBy:'-'"

EXPLANATION
if you leave the second parameter a blank string, then Angular will sort by the default order of the array (index), adding true at the end will enable the reverse parameter of Angular' orderBy

5
votes

Please use directly Java-script slice function with reverse like this:

data-ng-repeat="item in items.slice().reverse()"
3
votes

What is the structure of a single feed? It seems you can use the built-in filter from angular to order it the way you want. For example, if the field "id" is what provides "order" in the array, you would do this:

data-ng-repeat='feed in feeds | orderBy:id' 

If you want that reversed, you just do:

data-ng-repeat='feed in feeds | orderBy:id:reverse'

Does that make sense? Not sure you need your own filter. If that is the case, perhaps try debugging (i.e. write to the console or otherwise) to see what you are actually being passed. If it is not an array, that's your problem, otherwise try this instead:

return Array.prototype.slice.call(items).reverse(); 

Let me know if either of those work for you!

1
votes

Hope this will solve your problem

data-ng-repeat='feed in feeds.reverse()'
0
votes

a solution which doesn't sort the array, but only copies and reverses it: ng-repeat="item in items | orderBy : '[]': true"

0
votes

Another Alternative Way to Achieve the AngularJs Reverse is

<div ng-repeat="item in items | orderBy:'$index':true">
  <code>{{item.id}} - {{item.name}}</code>
</div>