AngularJS 使用 date() 格式时 orderBy 不起作用

AngularJS orderBy does not work when use date() format

OrderBy:'date' 工作正常,但不幸的是,当 addedit date() 时它没有正确排序

<tr ng-repeat="expense in filteredlist = (expenses | filter:filterlist) | pagination: currentPage : numPerPage | orderBy:'date'">

演示:http://codepen.io/anon/pen/VLRRpq

您的问题是旧日期作为字符串进行比较,而添加的新日期是 Date 对象。

将所有旧日期转换为日期对象是解决此问题的一种方法:

$scope.expenses = [/* your data */];
$scope.expenses.forEach(function(expense){ 
    expense.date = new Date(expense.date); 
});

(Codepen 更新:http://codepen.io/anon/pen/jPJJGV

反之亦然——在节省新费用时将日期转换为(格式正确的)字符串:

$scope.addExpense = function () {
    $scope.newexpense.date =  $scope.newexpense.date.toISOString();
    /* The rest of your creating code */
}

(Codepen 已更新以显示此方法:http://codepen.io/anon/pen/oXVVoJ

以上路径的选择将取决于您的情况;您必须考虑多种因素,例如您如何使用数据(即您是否需要对数据执行类似日期的操作?然后使用第一个解决方案),服务器如何期望它(服务器是否需要 ISOStrings?如果是,请使用第二种解决方案)等

但两者显然都适用于更新的 Codepen 解决方案。

您的初始日期是一个等字符串,而编辑日期是一个 javascript 日期对象,它被转换为一个字符串(出于某种原因,添加了引号)。 我通过在您的保存功能中添加 toIsoString() 更新了您的笔。 参见 http://codepen.io/rsids/pen/VLRRMR?editors=101