Angular-数据表按日期排序错误

Angular-Datatables wrong sorting on date

我在我的项目中使用 angular-datatables 插件,它适用于所有类型,除了日期。

示例描述:

A​​SC 示例:

我在我的 ng-repeat 中使用 Angular 方法和日期过滤器。我怀疑它以错误的日期格式排序。我希望它根据日期进行排序。我该如何解决这个问题?

<table class="table table-hover" datatable="ng">
        <thead>
            <tr>
                <th>Client</th>
                <th>Project</th>
                <th>ID</th>
                <th>Inv. Date</th>
                <th>Start Date</th>
                <th>End Date</th>
                <th>DKK ex VAT</th>
                <th>CIG</th>
                <th>Attention</th>
                <th>Cust. Manager</th>
                <th>Regarding</th>
                <th>Due Date</th>
                <th>Finalized</th>
                <th>Paid</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="invoice in vm.latestInvoices.LatestInvoices">
                <td>{{invoice.CompanyName}}</td>
                <td>{{invoice.ProjectName}}</td>
                <td>{{invoice.InvoiceID}}</td>
                <td>{{invoice.InvoiceDate | date: 'dd/MM/yyyy'}}</td>
                <td>{{invoice.InvoiceStart | date: 'dd/MM/yyyy'}}</td>
                <td>{{invoice.InvoiceEnd | date: 'dd/MM/yyyy'}}</td>
                <td>{{invoice.DKKexVAT}}</td>
                <td>{{invoice.CustomerInvoiceGroup}}</td>
                <td>{{invoice.Attention}}</td>
                <td>Customer Manager</td>
                <td>{{invoice.Regarding}}</td>
                <td>{{invoice.DueDate | date: 'dd/MM/yyyy'}}</td>
                <td>No</td>
                <td>{{invoice.Paid}}</td>
            </tr>
        </tbody>
    </table>

dataTables 通常可以很好地检测每一列的数据类型。但是,如果类型检测遇到 anything 与例如假设的数字冲突,则该列将变为默认的 alpha 排序。我坚信这里就是这种情况——如果呈现的内容 100% 满足 dd/MM/yyyy 标准,那么 dataTables 应该自动将该列排序为 date.

幸运的是,我们可以通过 columns / columnDefs 设置强制使用 date 数据类型。使用例如 DTColumnDefBuilder :

$scope.dtColumnDefs = [  
    DTColumnDefBuilder.newColumnDef([3,4,5,11]).withOption('type', 'date')
];

这会强制第 3、4、5 和 11 列为 date 类型。在标记中包含 dtColumnDefs

<table class="table table-hover" datatable="ng" dt-column-defs="dtColumnDefs">

示例 - 尝试注释掉 .withOption('type', 'date') 并查看差异 -> http://plnkr.co/edit/XpBcLhlm0Frq3voN6X97?p=preview

虽然晚了,但对于那些想要更多灵活性的人来说,还有另一种方法。

您可以按照Ultimate Date / Time sorting plugin中提到的方式解决排序问题。

代码真的很简单:

jQuery.fn.dataTable.moment('DD/MM/YYYY');

您可以从数据表CDN导入插件:

  <script src="https://cdn.datatables.net/plug-ins/1.10.13/sorting/datetime-moment.js"></script>


注意:您需要在应用程序中包含 momentJs 才能使用该插件。

我通过创建过滤器解决了这个问题

daterFilter.js

angular.module("app").filter("dateFilter", function(){
  return function(input) {
    var o = input.replace(/-/g, "/"); // Replaces hyphens with slashes if dd/mm/YYYY format
    return Date.parse(o + " -0000");
  };
});

在html文件中

<span>[[ ::created_at | dateFilter | date:"dd/MM/yyyy HH:mm"]]</span>

前段时间我在这个堆栈中看到了这个答案:

AngularJS: How to format ISO8601 date format?