0

How Angular orderBy with date string? I am trying to use the orderBy to sort a ng-repeat. Our data currently uses the valueList for the filter which isn't working.

I believe they are sorting alphanumerically rather than by date because my 'matchDate' field is a string. My question is, how to best convert this field to Date for proper ordering

$scope.valueList=
[
    {
        "_id" : ObjectId("5862c276d9913952fa80aa11"),
        "matchDate" : "31 December, 2016",
        "scoreStatus" : "OPEN"
    },
    {
        "_id" : ObjectId("58679badd991390f83fbb994"),
        "matchDate" : "30 December, 2016",
        "scoreStatus" : "CLOSE"
    },
    {
        "_id" : ObjectId("58679badd991390f83fbb994"),
        "matchDate" : "28 December, 2016",
        "scoreStatus" : "OPEN"
    }
]

This is my html

<div ng-repeat="eachValue in valueList | orderBy: 'matchDate'">
    {{eachValue.matchDate}}
</div>
Aravi S
  • 109
  • 1
  • 3
  • 10
  • If I'm not misunderstanding the question - is this what you're after? http://stackoverflow.com/questions/25515431/ng-repeat-filtering-data-by-date-range – Kevin Friedheim Dec 31 '16 at 07:25

2 Answers2

0

you can sort by date like this example:

<!DOCTYPE html>
 <html lang="en-US">
   <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
   <body>
    <script type="text/javascript">
       angular.module('app',[]).controller('test',function($scope){
         $scope.valueList=[{
         "_id" : "5862c276d9913952fa80aa11",
         "matchDate" : "31 December, 2016",
         "scoreStatus" : "OPEN"
        },{
         "_id" : "58679badd991390f83fbb994",
         "matchDate" : "30 December, 2016",
         "scoreStatus" : "CLOSE"
       },{
         "_id" : "58679badd991390f83fbb994",
         "matchDate" : "28 December, 2016",
         "scoreStatus" : "OPEN"
     }]

         $scope.myValueFunction = function(date) {
            return new Date(date) 
         };
     })
    </script>
    <div ng-app="app" ng-controller="test">
      <div ng-repeat="eachValue in valueList | orderBy: myValueFunction">
        {{eachValue.matchDate}}
      </div>
     </div>
  </body>
</html>
kamlesh
  • 238
  • 1
  • 5
0

I would suggest using a custom filter such as this:

app.filter('orderByDate', function() {
  return function(items) {
    // write your logic for order by  date
    // then return results as items    items= results;
    return items;
  };
});

for the write logic of orderby date you can use moment.js library

<div ng-repeat="eachValue in valueList | orderByDate>
    {{eachValue.matchDate}}
</div>

if you have problem contact

Niroshan Ranapathi
  • 3,007
  • 1
  • 25
  • 35