javascript - Angular ng-repeat 表:来自对象的动态列
问题描述
我正在尝试创建一个如下所示的表:
20 23 25 26
734.53 279.20 936.95 584.50
基于此对象:
{
"20": 734.5339864003384,
"23": 279.20378246766563,
"25": 936.9526667106079,
"26": 584.5060233468447,
"27": 279.20378246766563,
"28": 2055.970661511549,
"29": 1405.0981690224412,
"30": 549.4917661928141,
"31": 2329.1464674575695,
"32": 147.8822594632703,
"33": 698.0104349592335
}
显然,列的标题需要根据 JSON 的键是动态的,并且值应该对应。
我有以下代码,但我完全不确定我是否走在正确的轨道上:
JS
$scope.modal = {};
$scope.modal.keys = [];
$scope.modal.data = [];
for (var key in assets.total) {
if (assets.total.hasOwnProperty(key)) {
$scope.modal.keys.push(key);
$scope.modal.data.push(assets.total[key]);
}
}
HTML
<table class="table table-striped">
<thead>
<tr>
<th ng-repeat="th in modal.key">{{th}}</th>
</tr>
</thead>
<tbody></tbody>
<tr ng-repeat="x in modal.data">
<td ng-repeat="th in modal.key">{{x[th]}}</td>
</tr>
</tbody>
</table>
它只是不工作我只有一列得到一个奇怪的结果。
解决方案
你可以试试这个解决方案
用于ng-repeat="(key, value) in Array"
获取对象中的键值。
我在 Stackblitz 上的 Working Demo创建了一个演示
并删除for (var key in assets.total)
循环。
html代码
<table class="table table-striped">
<thead>
<tr>
<th ng-repeat="(key, value) in data"> {{key}} </th>
</tr>
<tr>
<td ng-repeat="(key, value) in data"> {{ value| number: 2 }} </td>
</tr>
</tbody>
</table>
js文件代码
$scope.data = {
"20": 734.5339864003384,
"23": 279.20378246766563,
"25": 936.9526667106079,
"26": 584.5060233468447,
"27": 279.20378246766563,
"28": 2055.970661511549,
"29": 1405.0981690224412,
"30": 549.4917661928141,
"31": 2329.1464674575695,
"32": 147.8822594632703,
"33": 698.0104349592335
}