如何按年份和降序对数据进行分组(较旧到较旧),然后在每个组内按降序排列项目?
我正在使用角度和下划线。
小提琴链接: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>
来源:
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');
}
答案 0 :(得分:2)
函数_.groupBy返回一个对象,你不能使用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
答案 1 :(得分:0)
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();