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?

DarkLeafyGreen
  • 69,338
  • 131
  • 383
  • 601

9 Answers9

222

According to documentation you can use the reverse argument.

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

Change your filter to:

orderBy: 'created_at':true
CD..
  • 72,281
  • 25
  • 154
  • 163
  • 22
    Note its `:` not a comma. (For other non-observant people) – ReactiveRaven Jul 15 '13 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 '16 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 07 '16 at 11:39
  • link to the documentation is broken – robert Jun 03 '18 at 19:20
183

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.

Ludwig Magnusson
  • 13,964
  • 10
  • 38
  • 53
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.

igorauad
  • 648
  • 2
  • 8
  • 11
  • 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 '15 at 07:06
  • This is correct method.. we can use this method in any date format.. thanks boss – Jethik Sep 13 '16 at 06: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/

Niels Bom
  • 8,728
  • 11
  • 46
  • 62
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>
Dinesh Vaitage
  • 2,983
  • 19
  • 16
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>
Michael
  • 239
  • 3
  • 9
  • 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 – cre8value Oct 22 '14 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>
ccampisano
  • 23
  • 7
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"
pabloRN
  • 866
  • 10
  • 19
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>
Abdo-Host
  • 2,470
  • 34
  • 33