Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse the order of Angular ngRepeat by object's keys which are numeric

Using Angular JS's ngRepeat directive, how can I make it so that the resulting iterations go in the reverse order? I am using an object where the keys are numbers, and I'd like to sort by those, descending.

I know that you can't really sort an object by keys like this (without keeping a reference to an array), but is this at all possible with Angular?

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>

<body>
  <script>
    var app = angular.module('myApp', []);
    app.filter('orderObjectBy', function() {
      return function(items, field, reverse) {
        var filtered = [];
        angular.forEach(items, function(item) {
          filtered.push(item);
        });
        filtered.sort(function(a, b) {
          return (a[field] > b[field] ? 1 : -1);
        });
        if (reverse) filtered.reverse();
        return filtered;
      };
    });
    app.controller('myController', ['$scope',
      function($scope) {
        $scope.data = {
          2013: 'oldest 4',
          2014: 'older 3',
          2015: 'new 2',
          2016: 'newest 1'
        };
      }
    ]);
  </script>
  <div id="myApp" ng-app='myApp' ng-controller="myController">
    <div ng-repeat="(date,text) in data">{{text}}</div>
    <hr/>
    <div ng-repeat="(date,text) in data | orderBy:date:reverse">{{text}}</div>
    <hr/>
    <div ng-repeat="(date,text) in data | orderBy:'-date'">{{text}}</div>
    <hr/>
    <div><b>Correct Answer!:</b></div><hr/>
    <div ng-repeat="(date,text) in data | orderObjectBy:date:true">{{text}}</div>
  </div>

</body>

For example, i'd like this to sort from Most recent to Oldest (the opposite of what it does in this code)

like image 356
d-_-b Avatar asked Apr 07 '15 05:04

d-_-b


1 Answers

ng-repeat doen't work with object for it you need to create your custom filter.

 <div ng-repeat="(date,text) in data | orderObjectBy:date:true">{{text}}</div>

app.filter('orderObjectBy', function() {
  return function(items, field, reverse) {
    var filtered = [];
    angular.forEach(items, function(item) {
      filtered.push(item);
    });
    filtered.sort(function (a, b) {
      return (a[field] > b[field] ? 1 : -1);
    });
    if(reverse) filtered.reverse();
    return filtered;
  };
});

Plunker

Hope it helps :)

like image 75
squiroid Avatar answered Nov 05 '22 12:11

squiroid