Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse an array in angular js without creating a filter

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

like image 220
Sajith Avatar asked Dec 16 '13 12:12

Sajith


People also ask

How do you reverse an array without any existing function?

In this method, the idea is to use a negative sign but by storing it into a variable. By using this statement x = (INT_MIN/INT_MAX), we get -1 in a variable x. As INT_MIN and INT_MAX have same values just of opposite signs, so on dividing them it will give -1. Then 'x' can be used in decrementing the index from last.

How do you reverse an array without using .reverse in JavaScript?

function reverse(array){ var output = []; for (var i = 0; i<= array. length; i++){ output. push(array. pop()); } return output; } console.

How do you reverse an array without modifying it?

To reverse an array without modifying the original, call the slice() method on the array to create a shallow copy and call the reverse() method on the copy, e.g. arr. slice(). reverse() . The reverse method will not modify the original array when used on the copy.


1 Answers

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

like image 52
Zim Avatar answered Nov 12 '22 08:11

Zim