orderBy dd / mm / yyyy by year angular

时间:2015-11-16 17:34:18

标签: angularjs date

我从网络服务收到的数据格式为dd / mm / yyyy。这个问题是在排序时,它按dd而不是yyyy排序。

<td ng-repeat="thead in resultHeader">
    <a href="" ng-click="order(thead.line)">{{thead.head}}</a>
    <span class="sortorder" ng-show="predicate === thead.line" ng-class="{reverse:reverse}"></span>
</td>

控制器:

$scope.order = function(predicate) {
    var results = $scope.model.resultList;
    $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
    $scope.predicate = predicate;
    $scope.model.currentPage = 1;
    $scope.model.beginFrom = 0;
};

如何通过yyyy对我当前设置的数据进行排序?

{
  "name": "Test",
  "ShipmentDate": "06\/08\/2012"
}

3 个答案:

答案 0 :(得分:3)

关键部分是向模块添加$filter并使用该$ filter从字符串中获取Date值。您可以使用Date.parse('dd/mm/yyyy')来获取浮点时间,然后对数据运行Array.sort()。

答案 1 :(得分:2)

如果您将日期字符串转换为Date个对象,则可以使用orderBy:过滤器按日期排序。

<td ng-repeat="thead in resultHeader | orderBy:'ShipmentDate':shouldBeReversedOrder ">
    <a href="" ng-click="shouldBeReversedOrder = !shouldBeReversedOrder">{{thead.head}}</a>
    <span class="sortorder" ng-show="predicate === thead.line" ng-class="{reverse:reverse}"></span>
</td>

如果您想以合适的格式显示日期,可以使用{{thead.ShipmentDate | 'yyyy-mm-dd'}}为您格式化日期。

答案 2 :(得分:2)

使用自定义订单。看:

function MyCtrl($scope, orderByFilter) {
    $scope.sortedFriends = [
    {
        name: 'John',
        age: 25,
        dateTest: '10/10/2015'
    }, {
        name: 'Jimmy',
        age: 25,
        dateTest: '10/12/2015'
    },{
        name: 'Mary',
        age: 28,
        dateTest: '10/09/2009'
    }, {
        name: 'Ed',
        age: 27,
        dateTest: '30/03/2014'
    },{
        name: 'Andrew',
        age: 27,
        dateTest: '11/11/2016'
    }];
    
    $scope.orderByCustom = function(friend) {
        console.log(friend)
       return friend.dateTest.split('/')[2];
    };
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="MyCtrl">
    <ul>
        <li ng-repeat="friend in sortedFriends | orderBy:orderByCustom"">
           {{friend}}
        </li>
    </ul>
</div>