我写了这篇方便的文章来按对象的多个列/属性进行排序。每次连续单击列时,代码都会存储最后单击的列,并将其添加到不断增长的单击列字符串名称列表中,将它们放置在名为 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>