【问题标题】:How to properly access nested elements using ng-repeat?如何使用 ng-repeat 正确访问嵌套元素?
【发布时间】:2023-03-11 11:15:01
【问题描述】:

我有以下 JSON 对象可以使用 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

我希望它能够根据表头打印表格,所以在

“BUILDING ID”将只有 3 个项目(Nexon、Kodak 和 Lion)和“TECHNOLOGY”

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

【问题讨论】:

    标签: json html-table nested angularjs-ng-repeat pug


    【解决方案1】:

    您需要“转置”数据以形成表格网格。目前,您的数据更适合每列布局多行,而不是使用ng-repeat 生成表格单元格时要求的每行多列。

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

    $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 库,但你可以不用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-05
      • 1970-01-01
      • 1970-01-01
      • 2017-12-05
      相关资源
      最近更新 更多