先降序分组再降序排序

Grouping with descending order and then sorting with descending order

如何按年份和降序(从新到旧)对数据进行分组,然后在每个组中再次按降序对项目进行排序?

我正在使用 angular 和下划线。

fiddle link: http://jsfiddle.net/xgxfqrgv/1/


现在的输出是:

2014
Cranberry

2015
Banana
Apple

但应该是:

2015
Apple
Banana

2014
Cranberry

html 来源:

<div ng-controller="MyCtrl">
  <div ng-repeat="(year, fulldata) in all | orderBy: 'year':true">
      <br>
      <u>{{year}}</u>
    <div ng-repeat="data in fulldata | orderBy: 'date':true">
        {{data.name}}
    </div>
  </div>
</div>

js 来源:

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {   
  var _all = [
    { year: 2015, date: "1. 5. 2015", name: "Banana" },
    { year: 2014, date: "1. 10. 2014", name: "Cranberry"},
    { year: 2015, date: "1. 10. 2015", name: "Apple" }
  ];

  $scope.all = _.groupBy(_all, 'year');
}
function MyCtrl($scope) {
    var _all = [{
        year: 2015,
        date: "1. 5. 2015",
        name: "Banana"
    }, {
        year: 2014,
        date: "1. 10. 2014",
        name: "Cranberry"
    }, {
        year: 2015,
        date: "1. 10. 2015",
        name: "Apple"
    }];

    $scope.all = _.groupBy(_all, 'year');
    console.log($scope.all);

    $scope.all[2015] = _.sortBy($scope.all[2015], 'date');
    console.log($scope.all);
}

注意:您应该遍历对象的属性并应用排序,而不是 $scope.all[2015] = _.sortBy($scope.all[2015], 'date');。如果要切换排序顺序,修改为$scope.all[2015] = _.sortBy($scope.all[2015], 'date').reverse();

即可

函数 _.groupBy returns 一个对象,您不能使用 ng-repeat 对对象进行排序。您可以做的是将对象转换为数组:

$scope.all = _.map( $scope.all, function(data, year){
    return {
        year: year,
        data: data
    }
})

然后在视图中有如下内容(年份前的减号表示降序):

<div ng-repeat="group in all | orderBy: '-year'">
   <br>
   <u>{{group.year}}</u>
   <div ng-repeat="yearsdata in group.data | orderBy: 'date'">
      {{yearsdata.name}}
   </div>
</div>

已更新fiddle