How can I reverse ng repeat?


#1

Hi, I don’t know why I got the reverse json data.

in my resource url, it is order by newest:

but after I use $http.get and console log the data, i found it is reverse:

plz advise how to solve that. Thx!


#2

So it seems styles is an object not an array. I think you could do something like this:

ng-repeat="(key, value) in styles | orderBy:'key'"

#3

Why not just use the standard reverse array function?


#4

that wont work beacause its not an array


#5

Your result is an object so the data is not ordered at all. Rather, your browser decided to show the contents of the object in alphanumerical order.


#6

The Chrome developer console lists an objects properties in alphabetical order.

What happens if you use the following to iterate? Is it in the order you expect?

for (var property in object) {
    if (object.hasOwnProperty(property)) {
        // do stuff
    }
}

For what it’s worth though, if you require things in a certain order, I personally believe you should be using an array


#7

Hi tobbe,

I have tried your way, but failed, nothing changed.

here is the code in my template:

<a class="button" ng-repeat="(year,style) in styleInfo.styles">{{year}}</a>

and here is the code in my controlers.js:
.controller(‘StyleCtrl’, function($scope, $http, $ionicLoading, $stateParams) {

return $http.get('http://www.chemm.com/trade/api/style/id/' + $stateParams.styledId).then(function(response){
    styleInfo = response.data;
    $scope.styleInfo = styleInfo;
    console.log(styleInfo);
}, function(err) {
    console.error('ERR', err);
});

})

did I missed something? plz advise. thx


#8

Hi, can you give an example how to use this? I just tried and seems it is still not working. thx.


#9

Ok, this works for me:

<a class="button" ng-repeat="style in styleInfo.styles | orderBy:'year'">{{style.year}}</a>

return $http.get('http://www.chemm.com/trade/api/style/id/').then(function (response) {
        var styleInfo = response.data;
        $scope.styleInfo = styleInfo;
        console.log(styleInfo);
    }, function (err) {
        console.error('ERR', err);
    });

#10

thx, I will tried this one!


#11
// Create a function that reverses an array.
$scope.reverse = function (array) {
  var copy = [].concat(array);
  return copy.reverse();
};

<div ng-repeat="item in reverse(items)">

Usefull way to reserve an array, you can turn your JSON into an array by looping trough it.