我需要使用angular $filter('orderBy')
函数来排序数组,但是需要指定三个谓词回调,并且排序顺序需要是ASC,DESC,ASC。
我知道有很多方法可以解决多列排序问题,但我的问题是关于使用Angular的orderBy过滤器来实现它。
我提供的示例不是实际数据,而只是简化模型,因此更容易解释。
我知道您可以使用简单的属性名称来处理它:
$scope.arr = $filter('orderBy')($scope.arr, ['+year', '-month', '+payment']);
但是,我的orderBy代码如下所示:
$scope.arr = $filter('orderBy')($scope.arr, [
function(row) {
//complicated logic here...for demo just return the raw property
return row.year;
},
function(row) {
//complicated logic here...for demo just return the raw property
return row.month;
},
function(row) {
//complicated logic here...for demo just return the raw property
return row.payment;
}
], true);
}
使用我的函数数组方法,我似乎无法找到提供ASC,DESC,ASC排序顺序的方法。我可以使用第三个参数来翻转整个数组($filter('orderBy')($scope.arr,[...], true)
),但这不是我想要的。
我尝试过像这样形成阵列,但这也不起作用:
['+', function(row){return row.year;}, '-', function(row){return row.month}, '+', function(row){return row.payment;}]
我没有想法。有没有办法使用谓词函数回调并仍然获得每个属性指定的方向排序?
angular.module('app', []).controller('MyController', function($scope, $filter) {
var id = 0;
var arr = [];
//generate some dummy data
for (var year = 2000; year < 2010; year++) {
for (var month = 3; month > 0; month--) {
for (var payment = 100; payment < 300; payment = payment + 50) {
var row = {
id: id++,
year: year,
month: '0' + month,
payment: payment
};
arr.push(row);
}
}
}
$scope.arr = arr;
$scope.order = function() {
$scope.arr = $filter('orderBy')($scope.arr, [
function(row) {
return row.year;
},
function(row) {
return row.month;
},
function(row) {
return row.payment;
}
], true);
}
//sort the array right away
$scope.order();
});
&#13;
th {
padding: 10px 20px;
border: 1px solid black;
background-color: lightgrey;
text-align: center;
}
td {
padding: 10px 20px;
border: 1px solid red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="MyController">
<table>
<tr>
<th>ID</th>
<th>Year</th>
<th>Month</th>
<th>Payment</th>
</tr>
<tr ng-repeat="row in arr">
<td>{{row.id}}</td>
<td>{{row.year}}</td>
<td>{{row.month}}</td>
<td>{{row.payment}}</td>
</tr>
</table>
</div>
</div>
&#13;
答案 0 :(得分:0)
你能试试吗?
function(row) {
//complicated logic here...for demo just return the raw property
return row.year;
},
function(row) {
//complicated logic here...for demo just return the raw property
return -1*row.month;
},
function(row) {
//complicated logic here...for demo just return the raw property
return row.payment;
}