在Angular中表示未知维度的json数组

时间:2015-01-05 17:09:04

标签: angularjs

我们说我有一个这样的数组:

[
    {
        "key1": "value1",
        "key2": "value2",
        "key3": "value3",
        "key4": "value4",
    },
    {
        "key1": "value5",
        "key2": "value6",
        "key3": "value7",
        "key4": "value8",
    }
]

是否可以在不知道密钥数量的情况下创建表格?像这样:

<table>
    <thead>
        <tr>
            <th ng-repeat="key in keys">
        </tr>
    </thead>
    <tbody>
        <tr>
            <td ng-repeat="value in values">
        </tr>
    </tbody>
</table>

2 个答案:

答案 0 :(得分:1)

尝试以下:

HTML

<table>
    <thead>
        <tr>
            <th ng-repeat="col in keyObj">{{col}}</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="key in keys">
            <td ng-repeat="col in key"> {{col}} </td>
        </tr>
    </tbody>
</table>

控制器:

app.controller('MainCtrl', function($scope) {
   $scope.keys = [
    {
        "key1": "value1",
        "key2": "value2",
        "key3": "value3",
        "key4": "value4",
    },
    {
        "key1": "value5",
        "key2": "value6",
        "key3": "value7",
        "key4": "value8",
    }];

    $scope.keyObj = Object.keys($scope.keys[0]);
});

工作样本here

答案 1 :(得分:0)

你能以另一种方式获得答案吗?所以你没有key.key1key.key2。我将格式化JSON响应如下:

[
    keys:[
        1:"key1",
        2:"key2",
        3:"key3",
        4:"key4"
    ],
    values: [
     1: [
            "value5",
            "value6",
            "value7",
            "value8"
        ],
     2: [
            "", "", "", ""
        ]
    ]
]

无论如何,我会尽量避免在视图中使用自定义json字段,因为它们将来可能会发生变化。