我有一个使用Angular 1.6动态生成的表。数据来自JSON格式的Web API。这是一个数据样本。
{
"CallData": [
{
"TableHeaders": [
{
"id": "0",
"text": "Time"
},
{
"id": "1",
"text": "January"
},
{
"id": "2",
"text": "February"
}
],
"TableRows": [
{
"id": "0",
"cells": [
{
"id": "0",
"text": "7:00"
},
{
"id": "1",
"text": "0"
},
{
"id": "2",
"text": "0"
}
]
},
{
"id": "1",
"cells": [
{
"id": "0",
"text": "8:00"
},
{
"id": "1",
"text": "18"
},
{
"id": "2",
"text": "83"
}
]
}
]
}
]
}
以下是生成表格的HTML:
<table>
<thead>
<tr>
<th ng-repeat="header in data.TableHeaders">
{{header.text}}
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in data.TableRows">
<td ng-repeat="cell in row.cells">
{{cell.text}}
</td>
</tr>
</tbody>
</table>
我希望能够在点击标题时对数据进行排序。但是,我到目前为止尝试使用id
为标题的ng-click
设置排序变量,我可以看到它更新了变量,但它没有对数据进行排序。这是使用ng-repeat="row in data.TableRows | orderBy: sortVar"
我的分类代码:
// Initialise variable
$scope.sortVar = '0';
<!-- HTML snippet -->
<th ng-repeat="header in data.TableHeaders" ng-click="updateSort(header.id)"></tr>
// function
$scope.updateSort = function(id) {
$scope.sortVar = id;
}
有什么方法可以对我的动态表进行排序吗?我是否需要为我的JSON数据添加另一个值才能执行此操作?
我对角度相对较新,所以不是百分之百确定如何实现这一目标。
如果有什么不清楚的地方,请告诉我,我会尝试更好地解释一下。
干杯
答案 0 :(得分:2)
这种类型有点复杂,因为它需要进入嵌套数组和对象。以下是使用JavaScript Array的排序函数如何实现它的示例:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.updateSort = function(index) {
$scope.data.TableRows = $scope.data.TableRows.sort(function(rowA, rowB) {
return rowA.cells[index].text.localeCompare(rowB.cells[index].text);
});
}
$scope.sortVar = '0';
$scope.data = {
"TableHeaders": [{
"id": "0",
"text": "Time"
}, {
"id": "1",
"text": "January"
}, {
"id": "2",
"text": "February"
}],
"TableRows": [{
"id": "0",
"cells": [{
"id": "0",
"text": "7:00"
}, {
"id": "1",
"text": "29"
}, {
"id": "2",
"text": "0"
}]
}, {
"id": "1",
"cells": [{
"id": "0",
"text": "8:00"
}, {
"id": "1",
"text": "18"
}, {
"id": "2",
"text": "83"
}]
}]
}
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<table>
<thead>
<tr>
<th ng-repeat="header in data.TableHeaders" ng-click="updateSort($index)">
{{header.text}}
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in data.TableRows" >
<td ng-repeat="cell in row.cells">
{{cell.text}}
</td>
</tr>
</tbody>
</table>
</body>
</html>
答案 1 :(得分:0)
我使用了分页指令(它易于使用)
https://github.com/michaelbromley/angularUtils/tree/master/src/directives/pagination
例:
http://www.expertphp.in/article/how-to-apply-search-sort-and-pagination-in-angularjs-example-using-dir-pagination-controls
演示:
http://demo.expertphp.in/search-sort-and-pagination-angularjs-example/