如何使用 ng-repeat 正确访问嵌套元素?

How to properly access nested elements using ng-repeat?

我有以下 JSON objects 可以使用 ng-repeat 访问。我在第一列中获取了所有名称,而不是分组到不同的列中。

$scope.tableItems = [
{
  "title": "BUILDING ID",
  "subtitle": [
    {
        "name": "Nexon"
    },
    {
        "name": "Kodak"
    },
    {
        "name": "Lion"
    }
  ]
},
{ 
  "title": "TECHNOLOGY",
  "subtitle": [
    {
        "name": "Robotic"
    },
    {
        "name": "AI"
    },
    {
        "name": "Algorithm"
  ]
}

];

我试过用jade这样访问它,

    table
        thead
            tr
                th(ng-repeat = "x in tableItems") {{ x.title }} //- get BUILDING ID and TECHNOLOGY
        tbody(ng-repeat = "x in tableItems")  //- get all the NAMEs
            tr(ng-repeat = "(key, value) in x.subtitle")
                td {{ value.name }}

结果返回

BUILDING ID                 TECHNOLOGY

Nexon

Kodak

Lion

Robotic

AI

Algorithm

我希望它能够根据tableheader打印table,所以在

"BUILDING ID" 将只有 3 个项目(Nexon、Kodak 和 Lion)并且 "TECHNOLOGY"

将有(机器人、人工智能和算法)。我的代码缺少什么?

您需要 "transpose" 您的数据以形成 table 网格。当前,您的数据更适合 table 来布局每列多行,而不是在使用 ng-repeat.

生成 table 单元格时需要在每行中布局多列

提取标题,并修改每行合并所有列:

$scope.tableHeadings = _.pluck($scope.tableItems, "title");
    var T = {};
    _.each($scope.tableItems, function (item, colind) {
        _.each(item.subtitle, function (row, rowind) {
            if (!_.has(T, 'r' + rowind)) {
                T['r' + rowind] = [];
            }
            T['r' + rowind].push({
                "name": row.name
            });
        });
    });

    $scope.tableRows = T;

然后在您的 HTML 中像这样使用它:

<table>
    <thead>
        <th ng-repeat="heading in tableHeadings">{{heading}}</th>
    </thead>
    <tbody>
        <tr ng-repeat="(key, columns) in tableRows">
            <td ng-repeat="col in columns">{{col.name}}</td>
        </tr>
    </tbody>
</table>

查看实际效果 here。我在这里使用了 Lodash 库,但你可以不用它。