Descending order by date filter in AngularJs
Asked Answered
U

9

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?

Unesco answered 28/4, 2013 at 9:12 Comment(0)
P
223

According to documentation you can use the reverse argument.

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

Change your filter to:

orderBy: 'created_at':true
Punch answered 28/4, 2013 at 9:15 Comment(4)
Note its : not a comma. (For other non-observant people)Cobweb
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"Campobello
These is working only for the page that having complete table data in a single page, but it will not work for the pagination..Theodoratheodore
link to the documentation is brokenSaltire
P
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.

Polyamide answered 28/4, 2013 at 9:23 Comment(1)
Thank you, this is a nice quick and easy way to reverse the order.Elfrieda
E
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.

Earing answered 5/8, 2014 at 17:24 Comment(2)
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.Augustineaugustinian
This is correct method.. we can use this method in any date format.. thanks bossLongevity
U
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/

Unkind answered 21/6, 2013 at 11:21 Comment(0)
D
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>
Doralyn answered 7/4, 2017 at 5:1 Comment(0)
M
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>
Monniemono answered 24/9, 2014 at 15:35 Comment(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?Heterogony
A
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>
Aloin answered 28/6, 2017 at 11:34 Comment(0)
M
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"
Moynihan answered 26/9, 2018 at 8:29 Comment(0)
H
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>
Hindgut answered 25/10, 2019 at 21:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.