我写了这个方便的文章来按对象的多个列/属性进行排序。每次连续单击列,代码都会存储最后单击的列,并将其添加到不断增加的单击列字符串名称列表中,并将它们放置在名为sortArray的数组中。内置的Angular“ orderBy”过滤器仅读取sortArray列表并按照存储在此处的列名的顺序对列进行排序。因此,最后单击的列名将成为主要的有序过滤器,前一个单击后会优先单击下一个,依此类推。反向顺序会立即影响所有列的顺序,并为整个数组列表集切换升/降序:
<script>
app.controller('myCtrl', function ($scope) {
$scope.sortArray = ['name'];
$scope.sortReverse1 = false;
$scope.searchProperty1 = '';
$scope.addSort = function (x) {
if ($scope.sortArray.indexOf(x) === -1) {
$scope.sortArray.splice(0,0,x);//add to front
}
else {
$scope.sortArray.splice($scope.sortArray.indexOf(x), 1, x);//remove
$scope.sortArray.splice(0, 0, x);//add to front again
}
};
$scope.sushi = [
{ name: 'Cali Roll', fish: 'Crab', tastiness: 2 },
{ name: 'Philly', fish: 'Tuna', tastiness: 2 },
{ name: 'Tiger', fish: 'Eel', tastiness: 7 },
{ name: 'Rainbow', fish: 'Variety', tastiness: 6 },
{ name: 'Salmon', fish: 'Misc', tastiness: 2 }
];
});
</script>
<table style="border: 2px solid #000;">
<thead>
<tr>
<td><a href="#" ng-click="addSort('name');sortReverse1=!sortReverse1">NAME<span ng-show="sortReverse1==false">▼</span><span ng-show="sortReverse1==true">▲</span></a></td>
<td><a href="#" ng-click="addSort('fish');sortReverse1=!sortReverse1">FISH<span ng-show="sortReverse1==false">▼</span><span ng-show="sortReverse1==true">▲</span></a></td>
<td><a href="#" ng-click="addSort('tastiness');sortReverse1=!sortReverse1">TASTINESS<span ng-show="sortReverse1==false">▼</span><span ng-show="sortReverse1==true">▲</span></a></td>
</tr>
</thead>
<tbody>
<tr ng-repeat="s in sushi | orderBy:sortArray:sortReverse1 | filter:searchProperty1">
<td>{{ s.name }}</td>
<td>{{ s.fish }}</td>
<td>{{ s.tastiness }}</td>
</tr>
</tbody>
</table>
orderBy:['-group','sub']
以group
相反的顺序排序。