144
<div class="recent" ng-repeat="reader in
    (filteredItems = (book.reader | orderBy: 'created_at' | limitTo: 1))">
</div>

So the book comes from rest api and it has many readers attached. I want to get the 'recent' reader.

The created_at field has the value which identifies the user as recent. But the above code gives me the oldest reader. So the order needs to be inversed? Is there some way to have the sorting in descending order?

9 Answers 9

222

According to documentation you can use the reverse argument.

filter:orderBy(array, expression[, reverse]);

Change your filter to:

orderBy: 'created_at':true
4
  • 22
    Note its : not a comma. (For other non-observant people) Jul 15, 2013 at 13:55
  • 1
    If you wanted a sort button you could replace true with sortDirection. Then in your scope set $scope.sortDirection = true. The click button would look like ng-click="sortDirection = !sortDirection"
    – mbokil
    Feb 23, 2016 at 17:38
  • 2
    These is working only for the page that having complete table data in a single page, but it will not work for the pagination..
    – ANK
    May 7, 2016 at 11:39
  • link to the documentation is broken
    – robert
    Jun 3, 2018 at 19:20
184

You can prefix the argument in orderBy with a '-' to have descending order instead of ascending. I would write it like this:

<div class="recent" 
   ng-repeat="reader in book.reader | orderBy: '-created_at' | limitTo: 1">
</div>

This is also stated in the documentation for the filter orderBy.

1
  • 6
    Thank you, this is a nice quick and easy way to reverse the order.
    – LukeP
    Oct 24, 2014 at 16:36
41

Perhaps this can be useful for someone:

In my case, I was getting an array of objects, each containing a date set by Mongoose.

I used:

ng-repeat="comment in post.comments | orderBy : sortComment : true"

And defined the function:

$scope.sortComment = function(comment) {
    var date = new Date(comment.created);
    return date;
};

This worked for me.

2
  • 1
    Thank you. My date's were strings entered in a MMMM dd, YYYY format, and I couldn't figure out how to get angular to sort them correctly unless I used a method that constructed a date object. Worked like a charm.
    – Zargoon
    Mar 10, 2015 at 7:06
  • This is correct method.. we can use this method in any date format.. thanks boss
    – Jethik
    Sep 13, 2016 at 6:40
17

And a code example:

<div ng-app>
    <div ng-controller="FooController">
        <ul ng-repeat="item in items | orderBy:'num':true">
            <li>{{item.num}} :: {{item.desc}}</li>
        </ul>
    </div>
</div>

And the JavaScript:

function FooController($scope) {
    $scope.items = [
        {desc: 'a', num: 1},
        {desc: 'b', num: 2},
        {desc: 'c', num: 3},
    ];
}

Will give you:

3 :: c
2 :: b
1 :: a

On JSFiddle: http://jsfiddle.net/agjqN/

7

Descending Sort by date

It will help to filter records with date in descending order.

$scope.logData = [
            { event: 'Payment', created_at: '04/05/17 6:47 PM PST' },
            { event: 'Payment', created_at: '04/06/17 12:47 AM PST' },
            { event: 'Payment', created_at: '04/05/17 1:50 PM PST' }
        ]; 

<div ng-repeat="logs in logData | orderBy: '-created_at'" >
      {{logs.event}}
 </div>
2

In my case, the orderBy is determined by a select box. I prefer Ludwig's response because you can set the sort direction in the select options as such:

        $scope.options = [
            { label: 'Title', value: 'title' },
            { label: 'Newest', value: '-publish_date' },
            { label: 'Featured', value: '-featured' }
        ]; 

markup:

<select ng-model="orderProp" ng-options="opt as opt.label for opt in options"></select>
<ul>
    <li ng-repeat="item in items | orderBy:orderProp.value"></li>
</ul>
1
  • 1
    this doesn't appear to work with custom sorting functions. Is there a way to reverse sort when using a custom orderBy function and selecting a parameter to order by from a <select> like in your example?
    – cre8value
    Oct 22, 2014 at 18:54
0

see w3schools samples: https://www.w3schools.com/angular/angular_filters.asp https://www.w3schools.com/angular/tryit.asp?filename=try_ng_filters_orderby_click

then add the "reverse" flag:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<p>Click the table headers to change the sorting order:</p>

<div ng-app="myApp" ng-controller="namesCtrl">

<table border="1" width="100%">
<tr>
<th ng-click="orderByMe('name')">Name</th>
<th ng-click="orderByMe('country')">Country</th>
</tr>
<tr ng-repeat="x in names | orderBy:myOrderBy:reverse">
<td>{{x.name}}</td>
<td>{{x.country}}</td>
</tr>
</table>

</div>

<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
    $scope.names = [
        {name:'Jani',country:'Norway'},
        {name:'Carl',country:'Sweden'},
        {name:'Margareth',country:'England'},
        {name:'Hege',country:'Norway'},
        {name:'Joe',country:'Denmark'},
        {name:'Gustav',country:'Sweden'},
        {name:'Birgit',country:'Denmark'},
        {name:'Mary',country:'England'},
        {name:'Kai',country:'Norway'}
        ];

    $scope.reverse=false;
    $scope.orderByMe = function(x) {

        if($scope.myOrderBy == x) {
            $scope.reverse=!$scope.reverse;
        }
        $scope.myOrderBy = x;
    }
});
</script>

</body>
</html>
0

My advise use moment() is easy to manage dates if they are strings values

//controller
$scope.sortBooks = function (reader) {
            var date = moment(reader.endDate, 'DD-MM-YYYY');
            return date;
        };

//template

ng-repeat="reader in book.reader | orderBy : sortBooks : true"
0

var myApp = angular.module('myApp', []);

myApp.filter("toArray", function () {
    return function (obj) {
        var result = [];
        angular.forEach(obj, function (val, key) {
            result.push(val);
        });
        return result;
    };
});


myApp.controller("mainCtrl", function ($scope) {

  $scope.logData = [
              { event: 'Payment', created_at: '10/10/2019 6:47 PM PST' },
              { event: 'Payment', created_at: '20/10/2019 12:47 AM PST' },
              { event: 'Payment', created_at: '30/10/2019 1:50 PM PST' }
          ]; 
        
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>

<div ng-app="myApp" ng-controller="mainCtrl">

  <h4>Descending</h4>
  <ul>
    <li ng-repeat="logs in logData | toArray | orderBy:'created_at':true" >
          {{logs.event}} - Date : {{logs.created_at}}
    </li>
  </ul>
  
  <br>
  
  
  <h4>Ascending</h4>
  <ul>
    <li ng-repeat="logs in logData | toArray | orderBy:'created_at':false" >
          {{logs.event}} - Date : {{logs.created_at}}
    </li>
  </ul>
  
</div>

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.