AngularJS - Can't sorted DateTime with ngRepeat orderBy

5.2k views Asked by At

After reading a tons of post on SO (post1, post2, post3 ...) and googling, I can't still figure out how to sort the datetimes inside my ng-repeat.

Here is what I've done :

The ng-repeat inside my index.html :

<div ng-repeat="oneItem in groupesItems.ITEMS | orderBy:'-myDate'" class="item">
                                        ...
 <div class="course-date">{[{oneItem.myDate | date:'dd MMMM yyyy hh : mm'}]}</div>
                                        ...
</div>

I've also read that I've to convert myDate to Date object, because Angular considers it as a string. So in my angular controller, this is what I've done :

($scope.groupesItems.ITEMS).forEach(function(data){
        data.myDate = new Date(data.myDate);
    });

But nothing is working !

Please Help ! what I've overlooking ?

1

There are 1 answers

2
Slava Utesinov On BEST ANSWER

Try to use some temp variable via getTime method:

<div ng-repeat="oneItem in groupesItems.ITEMS | orderBy:'-temp'" class="item">
    <div class="course-date">{[{oneItem.myDate | date:'dd MMMM yyyy hh : mm'}]}</div>
</div>

Javascript:

($scope.groupesItems.ITEMS).forEach(function(data){
     data.temp = new Date(data.myDate).getTime();
});

Also you can try reverse(true after orderBy:'myDate':) without changing javascript part:

<div ng-repeat="oneItem in groupesItems.ITEMS | orderBy:'myDate':true" class="item">
    <div class="course-date">{[{oneItem.myDate | date:'dd MMMM yyyy hh : mm'}]}</div>
</div>