【问题标题】:Sorting data by date using orderBy sorts data only by number of the day not by year. [AngularJS]使用 orderBy 按日期对数据进行排序仅按天数而不是按年份对数据进行排序。 [AngularJS]
【发布时间】:2018-02-24 11:26:19
【问题描述】:

我想在AngularJS中使用OrderBy按日期对数据进行排序,并在此基础上显示最新数据。

问题在于 orderBy 仅考虑当天对数据进行排序。我希望它考虑所有因素,例如月份和年份。

这是我正在处理的代码。

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>

【问题讨论】:

    标签: angularjs sorting date angularjs-orderby


    【解决方案1】:

    在角度方面,您可以从您拥有的日期添加一个日期对象并使用该属性进行过滤。

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

    将 changeLog.html 中的第一行更改为 &lt;div class="logArena" ng-repeat="log in $ctrl.logs | orderBy: '-dateObj'"&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-13
      • 1970-01-01
      • 2021-08-08
      • 2012-06-26
      • 2016-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多