当我的数据是嵌套的并且并非所有列都是对象的一级公民时,如何在 angularjs 中进行表排序。
数据(摘录)
[
{
"name": "Team A",
"categories": [
{
"label": "FG%",
"value": 4676,
"points": 7
},
{
"label": "FT%",
"value": 8387,
"points": 9
}
]
}, {
"name": "Team B",
"categories": [
{
"label": "FG%",
"value": 5285,
"points": 10
},
{
"label": "FT%",
"value": 6111,
"points": 1
}
]
}
]
HTML
<div ng-controller="mainCtrl">
<table class="table table-striped table-condensed">
<thead>
<tr>
<th ng:click="changeSorting('name')">Name</th>
<th ng:click="changeSorting('name')">Points</th>
<th ng:click="changeSorting(value.label)" ng-repeat="(index, value) in data.teams[0].categories">{{value.label}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="team in data.teams | orderBy:sort.column:sort.descending ">
<td>{{team.name}}</td>
<td>{{team.totalPoints}}</td>
<td ng-repeat="(name, cat) in team.categories">
{{cat.value}}
</td>
</tr>
</tbody>
</table>
</div>
这是我多次发现的方法。无论如何,由于我的数据结构,恐怕这不是正确的想法。
在 Controller 上排序
$scope.sort = {
column: 'name',
descending: false
};
$scope.changeSorting = function(column) {
var sort = $scope.sort;
if (sort.column == column) {
sort.descending = !sort.descending;
} else {
sort.column = column;
sort.descending = false;
}
};
这是更新后的 fiddle :http://jsfiddle.net/SunnyRed/mTywq/2/
最佳答案
我根据http://docs.angularjs.org/api/ng.filter:orderBy处的 Angular 文档修改了您的代码
HTML
<div ng-controller="mainCtrl">
<table class="table table-striped table-condensed">
<thead>
<tr>
<th ng:click="predicate = 'name'; reverse = !reverse">Name</th>
<th ng:click="predicate = 'totalPoints'; reverse = !reverse">Points</th>
<th ng:click="toggleSort($index)" ng-repeat="category in data.teams[0].categories">{{category.label}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="team in data.teams | orderBy:predicate:reverse">
<td>{{team.name}}</td>
<td>{{team.totalPoints}}</td>
<td ng-repeat="(name, cat) in team.categories">
{{cat.value}}
</td>
</tr>
</tbody>
</table>
</div>
对部件进行排序
$scope.toggleSort = function(index){
$scope.reverse = !$scope.reverse;
$scope.predicate = function(team){
return team.categories[index].points;
}
}
这是 fiddle :http://jsfiddle.net/mgalela/Br5Wb/14/
关于javascript - 数据嵌套时 AngularJs 表排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20019939/