Angular JS按日期排序dd-mm-yyyy

时间:2018-06-22 07:52:55

标签: angularjs

我要订购日期。但不能正常工作。日期格式为dd-mm-yyyy。只是订购dd格式不会检查mm和yyyy。我该怎么解决?

JS

    $scope.sortOptions = [                       
        {
            name:'Date desc',
            sortCategory:'-anndate'
        },            
        {
            name:'Date asc',
            sortCategory:'anndate'
        }       
    ];

HTML

    <select ng-model="selectedSortType" class="custom-select">
        <option value="" selected="">Select type</option>
        <option value='{{opt.sortCategory}}' ng-repeat="opt in sortOptions track by $index">{{opt.name}}</option>
    </select>  
   <div ng-repeat="i in res| orderBy:selectedSortType">
       <div>{{i.anndate}}</div>
   </div>

2 个答案:

答案 0 :(得分:1)

var app = angular.module('app', [])
    .controller('appController', appController);

appController.$inject = ['$scope', '$window'];

function appController($scope, $window) {

    $scope.title = "date sorting example";

    $scope.sortOptions = [{
            name: 'Date desc',
            sortCategory: '2018-07-15	'
        },
        {
            name: 'Date desc',
            sortCategory: '2018-07-12	'
        },
        {
            name: 'Date asc',
            sortCategory: '2018-07-13'
        }
    ];
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="appController">



<p>Ascending Order</p>
<div ng-repeat="i in sortOptions | orderBy:'sortCategory'">
  <p>{{i.sortCategory}}</p>
</div>
 <select ng-model="selectedSortType" class="custom-select">
        <option value="" selected="">Select type</option>
        <option value='{{opt.sortCategory}}' ng-repeat="opt in sortOptions | orderBy:'sortCategory'">{{opt.sortCategory}}</option>
    </select>  
<p>Descending Order</p>
<div ng-repeat="i in sortOptions | orderBy:'-sortCategory'">
  <p>{{i.sortCategory}}</p>
</div>
 <select ng-model="selectedSortType" class="custom-select">
        <option value="" selected="">Select type</option>
        <option value='{{opt.sortCategory}}' ng-repeat="opt in sortOptions | orderBy:'-sortCategory'">{{opt.sortCategory}}</option>
    </select>  
</div>

答案 1 :(得分:0)

尝试一下。

由于res对象中的日期为字符串格式,因此过滤器将对dd值应用

对于整个date过滤器,您需要将anndate转换为Date()对象
将以下代码放在在控制器中分配res值的下面的行中

angular.forEach($scope.res,function(item){ item.anndate = new Date(item.anndate); });

然后用html替换为下面的行

 <select ng-model="selectedSortType" class="custom-select">
        <option value="" selected="">Select type</option>
        <option value='{{opt.sortCategory}}' ng-repeat="opt in sortOptions track by $index">{{opt.name}}</option>
    </select>  
   <div ng-repeat="i in res| orderBy:selectedSortType">
       <div>{{i.anndate| date : 'dd/MM/yyyy'}}</div>
   </div>