[英]Grouping with descending order and then sorting with descending order
如何按年份和降序對數據進行分組(從新到舊),然后在每個組內再次按降序對項目進行排序?
我正在使用角度和下划線。
小提琴鏈接: 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');
}
函數_.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>
更新的小提琴
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.