我有一个动态数据集来呈现Angular.换句话说,我无法访问在运行时返回的列名.
我可以将列名称作为标题和数据本身显示没有问题. ng-repeat(或者它可能是JS本身)虽然拒绝按照创建的顺序返回列.您可以在小提琴中看到列被排序,因此它们显示为“年龄名称重量”,我需要它们的方式,“名称年龄重量”
我创建了另一个列名称数组及其正确的顺序($scope.order)但我似乎找不到使用Angular对数据进行排序的方法.
请给我一个以原始顺序显示此数据的方法.
我创建了一个JSfiddle:http://jsfiddle.net/GE7SW/
这是一个设置数据的简单范围:
function MainCtrl($scope) {
$scope.output = [
{
"name": "Tom","age": "25","weight" : 250
},{
"name": "Allan","age": "28","weight" : 175
},{
"name": "Sally","age": "35","weight" : 150
}
];
$scope.order = {
"name": 1,"age": 2,"weight" : 3
};
}
这是HTML:
<table ng-app ng-controller="MainCtrl">
<thead>
<tr>
<th ng-repeat="(key,value) in output.0">{{key}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in output">
<td ng-repeat="(key,value) in row">{{value}}</td>
</tr>
</tbody>
</table>
(注意我在本例中为ng-class代码需要最后一次ng-repeat中的(key,value).)
从不保证JavaScript对象中的属性顺序.您需要使用列表.
您需要做的唯一事情是将$scope.order转换为数组:
$scope.order = [
"name","age","weight"
];
并在HTML中使用它,如下所示:
<table ng-app ng-controller="MainCtrl">
<thead>
<tr>
<th ng-repeat="key in order">{{key}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in output">
<td ng-repeat="key in order">{{row[key]}}</td>
</tr>
</tbody>
</table>
Fiddle