【问题标题】:angular how to order item by date from format like "yyyy-mm-ddT00:00:00"角度如何从“yyyy-mm-ddT00:00:00”等格式按日期订购项目
【发布时间】:2015-01-15 12:17:12
【问题描述】:

我得到一个包含项目数的 json 对象

   "[{"StartDate":"2015-01-16T00:00:00","EndDate":"2015-01-20T00:00:00"},
    {"StartDate":"2015-01-15T00:00:00","EndDate":"2015-01-16T00:00:00"}]"

我想用 DESC 顺序在客户端的桌子上订购这个

这是请求并返回 json 答案的函数

  function getTrips() {

        //set loading indicator
        vm.searchData.isLoading = true;
        return datacontext.getTrips(vm.searchData.getTripsFilter)
            .success(function (result) {
                try {
                    //set loading indicator
                    vm.searchData.isLoading = false;
                    tripData.trips = result;
                    if (!tripData.trips) {
                        logWarning('dont find trips:(');
                        return;
                    }

                    //post-process trips for display
                    angular.forEach(tripData.trips, tripData.processTrip);

                    //start filtering trips pager
                    vm.searchData.filterTrips();
                    log('found' + tripData.trips.length + ' to this search.');

                    return tripData.trips;
                } catch (e) {
                    logError('error searching trips!', e);
                }
            })
            .error(function (data) {
                logError('error searching trips!', data);
                vm.searchData.isLoading = false;
            });
    }

我认为 mybe 添加全局参数来控制顺序(但我得到一个字符串),或者在 Angular 上有一个按日期自动排序的函数,我不知道:|

提前感谢您的帮助

【问题讨论】:

    标签: javascript json angularjs date


    【解决方案1】:

    如果您只是要求简单的排序,那么这里就是它

    HTML

    <div ng-controller="DatesCtrl">
        <div ng-repeat="d in dates | orderBy:identity:true" ng-bind="d | date:'medium'"></div>
    </div>
    

    Js

    var myApp = angular.module('myApp', []);
    
    myApp.controller('DatesCtrl', ['$scope', function($scope) {
        $scope.identity = angular.identity;
        $scope.dates = [ new Date("2015-01-16T00:00:00"), new Date("2015-01-15T00:00:00"), new Date("2015-01-17T00:00:00") ];
    
     }]);
    

    Example

    【讨论】:

    【解决方案2】:

    由于日期值的格式化方式,无论是按字母顺序将它们作为字符串排序,还是先将它们转换为 Date 对象,都将导致正确的排序。

    因此,您可以使用内置的orderBy 过滤器对数据进行排序。这可以在您的控制器中完成:

    tripData.trips = $filter('orderBy')(tripData.trips, 'StartDate', true);
    

    或者在你看来:

    <div ng-repeat="trip in trips | orderBy:'StartDate':true">...</div>
    

    https://docs.angularjs.org/api/ng/filter/orderBy

    【讨论】:

    • 哇,我不知道我可以按字母顺序排序,这太棒了,谢谢
    猜你喜欢
    • 1970-01-01
    • 2014-12-02
    • 2020-08-28
    • 1970-01-01
    • 2019-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-03
    相关资源
    最近更新 更多