【问题标题】:How to sort month and year in angularjs [duplicate]如何在angularjs中对月份和年份进行排序[重复]
【发布时间】:2018-11-24 00:30:41
【问题描述】:

我有一张带有月份和年份列的表格。如何对日期和年份进行排序。请检查小提琴。

在这种情况下,日期格式为“MMMM yyyy”。例如,我的要求是,

如果我的日期是“2016 年 8 月”、“2015 年 9 月”和“2018 年 1 月”。在这里,我想根据年份对日期进行排序。所以结果应该是这样的, “2015 年 9 月”、“2016 年 8 月”和“2018 年 1 月”。

如何在 angularjs 中做到这一点。

jsfiddle

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

   appController.$inject = ['$scope', '$window'];

   function appController($scope, $window) {

       $scope.title = "date sorting example";

       $scope.sortType = "name";
       $scope.sortReverse = true;

       var dateA = new Date("02/06/2016");
       dateA.setDate(dateA.getDate() + 2);
       var dateB = new Date("07/06/2017");
       dateB.setDate(dateB.getDate() + 4);
       var dateC = new Date("08/06/2016");
       dateC.setDate(dateC.getDate() + 7);
       var dateD = new Date("04/06/2018");
       dateD.setDate(dateD.getDate() + 20);

       $scope.allItems = [{
           date: dateA,
           name: "A"
       }, {
           date: dateB,
           name: "B"
       }, {
           date: dateC,
           name: "C"
       }, {
           date: dateD,
           name: "D"
       }];

   };
<div ng-controller="appController">

    <h1>This is my {{title}}</h1>
    <table class="table table-striped">
        <thead>
            <td data-ng-click="sortType = name; sortReverse = !sortReverse;">
                Date
            </td>
            <td data-ng-click="sortType = name; sortReverse = !sortReverse;">
                Name
            </td>
        </thead>
        <tbody>
            <tr ng-repeat="item in allItems">
                <td>{{item.date | date:"MMMM yyyy"}}</td>
                <td>{{item.name}}</td>
            </tr>
        </tbody>
    </table>

</div>

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    使用Array.sort

    var dateA = new Date("02/06/2016");
    dateA.setDate(dateA.getDate() + 2);
    var dateB = new Date("07/06/2017");
    dateB.setDate(dateB.getDate() + 4);
    var dateC = new Date("08/06/2016");
    dateC.setDate(dateC.getDate() + 7);
    var dateD = new Date("04/06/2018");
    dateD.setDate(dateD.getDate() + 20);
    
    let allItems = [{date: dateA,name: "A"}, {date: dateB,name: "B"}, {date: dateC,name: "C"}, {date: dateD,name: "D"}];
    
    allItems.sort((a,b) => a.date - b.date);
    
    console.log(allItems);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-01
      • 2012-01-11
      • 1970-01-01
      • 2019-12-06
      • 2015-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多