6

I am having an array in controller as follows

function FooController($scope) {
    $scope.items = ["a","b","c"];
}

I used ng-repeat to show the data in items,

<div ng-app>
    <div ng-controller="FooController">
        <ul ng-repeat="item in items">
            <li>{{item}}</li>
        </ul>
    </div>
</div>

I got the result as a,b,c order. I want to show it in reverse order. that means c,b,a without changing its order in the controller or without creating a filter. How to do that? Check this link

0

3 Answers 3

17

I faced the same problem, but with an array of objects. This quick solution worked for me, but using the filter is still the best practice.

<li data-ng-repeat="item in data.slice().reverse()">
      ...
</li>

http://bootply.com/SgVBZvZ708

Sign up to request clarification or add additional context in comments.

2 Comments

reverse() is a native javascript function... why you consider this a "dirty solution"?
This looks cleaner.
7

In order to avoid the writting of a custom filter, I suggest you to use this syntax :

  <ul ng-repeat="item in items |  orderBy:'-toString()'">

The documentation assume you sort an array of Objects but in your case there are just plain strings.

Comments

2

Wrap the strings in objects and use orderBy or create a new filter:

angular.module("app",[])
.filter("reverse", function(){
    return function(items){
        return items.slice().reverse(); // Create a copy of the array and reverse the order of the items
    };
});

And use it like this:

 <ul ng-repeat="item in items|reverse">

Updated fiddle (I've also updated the ng-app directive so it's passed the "app" module.)

1 Comment

When I stored my items I used items.slice().reverse(); now it's reversed pretty good.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.