[英]AngularJS ng-repeat dictionary with array value
使用AngularJS ng-repeat从不确定的JSON对象创建HTML表时遇到了麻烦。 我要完成的工作是使用通用格式输入JSON对象:
{
"My First Key" : [0, 1, 2 ..., n],
"My Second Key" : ["Val0", "Val1", ..., "Valn"],
...
"My Nth Key" : [0, 1, 2 ..., n]
}
并能够使用以下格式创建表:
My First Key | My Second Key | ... | My Nth Key |
0 | "Val0" | ... | 0 |
1 | "Val1" | ... | 1 |
... | ... | ... | ... |
n | "Valn" | ... | n |
字典中的所有值都是相等长度的数组。 键(IE:“我的第一键,我的第二键”的实际值)也是未知的。 数组的内容可以是字符串或数字。 每个数组中没有数据类型的混合。 同样重要的是要注意,当表达式求值时,我实际上并不知道与每个键对应的字符串是什么。
在myArray中使用ng-repeat =“(key,value)”(其中myArray是某些控制器中的上述数据结构)可以成功构建表头:
<table ng-controller="myController">
<tr>
<th ng-repeat="(key, value) in myArray">{{key}}</th>
</tr>
<tr ng-repeat="???">
<td>{{data}}</td>
</tr>
</table>
根据我给定的数据结构和限制,这可能吗? 如果是这样,如何在ng-repeat中访问value内的数组值? 需要注意的一点是,我能够通过同时显示几个单列表来创建所需结果的简陋版本(请参阅此JSFiddle )。 但是,我正在寻找一种更优雅的解决方案(一旦列中有太多列,我的简陋版本也会开始崩溃)。
您可以通过选择其中一列作为指南来进行此操作,然后对它们进行迭代以遍历每一行,从而产生$index
。 因此,您可以使用先前创建的行指南(也称为$parent.$index
)再次迭代列。
观察结果:如果您选择的列不适合适当的行数,它将使其他列停在相同的标记处,因此,如果您的指南列的行数少于其他列,则将仅呈现此行数。 因此,请确保所有列的行数均相同。
以下代码段实现了该解决方案。
angular.module('myApp', []) .controller('myController', function ($scope){ $scope.myArray = { "My First Key" : [0, 1, 2, 'n'], "My Second Key" : ["Val0", "Val1", 'Val2', 'Valn'], "My Nth Key" : ['a0', 'a1', 'a2' , 'an'] }; $scope.pivotKey = Object.keys($scope.myArray)[0]; }); angular.element(document).ready(function () { angular.bootstrap(document, ['myApp']); });
table{ border-collapse: collapse; } td,th { padding: 2px 4px; }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <table ng-controller="myController" border="1"> <tr> <th ng-repeat="(column, rows) in myArray">{{ column }}</th> </tr> <tr ng-repeat="(rowIndex, rowValue) in myArray[pivotKey]"> <td ng-repeat="value in myArray"> {{ value[rowIndex] }} </td> </tr> </table>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.