Search code examples
angularjssortingdateangularjs-orderby

Sorting data by date using orderBy sorts data only by number of the day not by year. [AngularJS]


I want to sort data by date using OrderBy in AngularJS and show the latest data on the basis of it.

The problem is that the orderBy is sorting data taking only the day into consideration. I want it to consider all the factors like month and year.

Here is the code I am working on.

script.js

angular.module('Timeline', [])
.component("changeLog", {
  templateUrl: 'changeLog.html',
  controller: ('timelineController', timelineController)
});
function timelineController() {
  this.logs = [
    {
      "date": "01/7/2022",
      "title": "Change Log1",
      "desc": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
      "link": "www.enquero.com"
    },
    {
      "date": "09/2/2018",
      "title": "User Analysis",
      "desc": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
      "link": "www.google.com"
    },
    {
      "date": "11/2/2019",
      "title": "User Analysis",
      "desc": "This cool new feature has been added recently, maybe you should have a look.",
      "link": "www.google.com"
    },
  ];
}

changeLog.html

<div class="logArena" ng-repeat="log in $ctrl.logs | orderBy: '-date'">

  <ul class="timeline">
    <li>
      <span class="direction-l">
        <span class="time-wrapper">
          <span class="time">
              {{log.date}}
          </span>
        </span>
      </span>

      <div class="direction-r">
        <div class="flag-wrapper">
          <div class="flag">{{log.title}}</div>
        </div>
        <div class="desc">
          {{log.desc}}
        </div>
      </div>

    </li>
  </ul>

Index.html

<!DOCTYPE html>
<html ng-app="Timeline">
  <head>
    <title>Timeline App</title>
    <link rel="stylesheet" href="style.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
    <script src="script.js"></script>
  </head>
  <body>
    <div>
      <center><h3>ChangeLog Wiki</h3></center>
      <change-log></change-log>
    </div>
  </body>
</html>

Solution

  • on angular side you can add a date object from the date you have and filter with that property.

    $scope.logs.forEach(function(log){
     log.dateObj = new Date(log.date);
    })
    

    change the first line in changeLog.html to <div class="logArena" ng-repeat="log in $ctrl.logs | orderBy: '-dateObj'">