按日期排序 AngularJS (Ionic

Order by Date AngularJS (Ionic

我正在尝试显示按日期排序的手风琴列表。这个日期是JSON格式,对用户不友好。然而,如果我按照我想要的方式格式化它,我就不能再用它来排序列表了。

.controller('WarningsCtrl', function ($scope, HttpService) {
    HttpService.getWarnings()
    .then(function (res) {
        for (var i = 0; i < res.length; i++){
            //converts json date (2017-01-25T16:10:45) in simple date (25-01-2017)
            //inicioArray = res[i].inicio.split("-");
            //inicioArray[2] = inicioArray[2].substring(0, inicioArray[2].indexOf("T"));
            //res[i].inicio = inicioArray[2] + "-" + inicioArray[1] + "-" + inicioArray[0];
        }
        $scope.warnings = res;
    }, function (err) {
        console.log("Error. " + err);
    });
    console.log("Warnings: " + $scope.warnings);
})
<ion-item-accordion class="item item-text-wrap" title="{{warning.titulo}}" date="{{warning.inicio}}" icon-align="right" icon-close="ion-chevron-right" icon-open="ion-chevron-down" style="font-size:10px!important; color:red;" ng-repeat="warning in warnings | orderBy:'-inicio'" >
    <div style="text-align:center" ng-if="warning.imagem != null"><img ng-src="http://www.predio24.com/{{warning.imagem}}" style="width:100%; height:auto" /></div><br />
    <div ng-bind-html="warning.corpo | unsafe"></div>
</ion-item-accordion>

如果我取消注释 JSON 日期转换,orderby 将不起作用,因为数字的顺序不利于排序。如何在使用原始日期订购时保留格式化日期?

在将日期提供给 Accordion 指令时,您是否尝试过使用 Angular 过滤器来格式化日期?您上面的注释代码可能是如下所示的过滤器函数(假设我已经正确解释了您的函数):

.filter('formatDate', function() {
    return function(rawDate) {
        //converts json date (2017-01-25T16:10:45) in simple date (25-01-2017)
        inicioArray = rawDate.split("-");
        inicioArray[2] = inicioArray[2].substring(0, inicioArray[2].indexOf("T"));
        return inicioArray[2] + "-" + inicioArray[1] + "-" + inicioArray[0];
    }
});

然后在您的手风琴标记中,日期将被插入为:

date="{{warning.inicio | formatDate}}" 

这应该让日期单独用于其他操作(如 orderBy),同时为指令提供格式化版本以供显示...

我没有过多探索 angularJS 过滤器,所以这个问题的解决方案比我想象的要简单。

我离开控制器时没有任何相关代码

.controller('WarningsCtrl', function ($scope, HttpService) {
    HttpService.getWarnings()
    .then(function (res) {
        $scope.warnings = res;
    }, function (err) {
        console.log("Error. " + err);
    });
    console.log("Warnings: " + $scope.warnings);
})

并在我看来使用了过滤器:

date="{{warning.inicio | date: 'dd/MM/yyyy' }}"

所以:

<ion-item-accordion class="item item-text-wrap" title="{{warning.titulo}}" date="{{warning.inicio | date: 'dd/MM/yyyy' }}" icon-align="right" icon-close="ion-chevron-right" icon-open="ion-chevron-down" style="font-size:10px!important; color:red;" ng-repeat="warning in warnings | orderBy:'-inicio'">