Search code examples
angularjsangularjs-ng-repeatangularjs-orderby

Angular JS orderBy is not working with Dates


orderBy feature is not working with the dates when i try to use in the ng-repeat

Here I wanted to sort the entried based on the executedOn

I wanted to sort element the latest date should be reflected at the top.

Can someone help me

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

app.controller('MainCtrl', function($scope) {

    $scope.details = [
  {
    "id": 255463,
    "orderId": 226433,
    "status": 1,
    "executedOn": "25/Sep/17",
    "executedBy": "Person A",
    "executedByDisplay": "Person A",
    "cycleId": 4042,
    "cycleName": "Cycle A",
    "versionId": 21289,
    "versionName": "Version A",
    "issueKey": "A"
  },
  {
    "id": 255433,
    "orderId": 226403,
    "status": 1,
    "executedOn": "1/Mar/17",
    "executedBy": "Person B",
    "executedByDisplay": "Person B",
    "cycleId": 4041,
    "cycleName": "Cycle B",
    "versionId": 21289,
    "versionName": "Version A",
    "issueKey": "B"
  },
  {
    "id": 255432,
    "orderId": 226402,
    "status": 1,
    "executedOn": "1/Apr/17",
    "executedBy": "Person B",
    "executedByDisplay": "Person B",
    "cycleId": 4041,
    "cycleName": "Cycle B",
    "versionId": 21289,
    "versionName": "Version A",
    "issueKey": "C"
  }
];
});
th, td {
    border-bottom: 1px solid #ddd;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="myApp">


  <body ng-controller="MainCtrl">
  <table class="table h6">
        <thead>
          <tr>
            <th>#</th>
            <th>Cycle Name</th>
            <th>Execution Completed</th>
            <th>Total Test Cases</th>
          </tr>
        </thead>
        <tr ng-repeat="x in details | orderBy :'executedOn'">
          <td>{{$index+1}}</td>
          <td>{{x.cycleName}}</td>
          <td>{{x.executedOn | date:'d-MMM-yy'}}</td>
          <td>{{x.versionName}}</td>
        </tr>
      </table>
  </body>

</html>


Solution

  • What about to convert "executedOn" to Date Object: new Date("25/Sep/17"),

    You can do that as:

    $scope.details.map(function(item){
        item.executedOn = new Date(item.executedOn);
        return item;
      });
    

    The sorting will work properly

        <tr ng-repeat="x in details | orderBy :'executedOn'">
          <td>{{$index+1}}</td>
          <td>{{x.cycleName}}</td>
          <td>{{x.executedOn | date:'d-MMM-yy'}}</td>
          <td>{{x.versionName}}</td>
        </tr>
    

    Demo Plunker