如何从AngularJS中的对象数组构建具有行距的表

时间:2018-11-14 10:57:58

标签: javascript angularjs html-table angularjs-ng-repeat

我有与此问题类似的问题:AngularJS repeat with table and rowspan

我想用对象的行跨度构建表。

但是我使用对象数组而不是单个对象作为表数据。

示例:

[
    {
        "key": "key 1",
        "values": [
                {
                    "value": "value-1"
                },
                {
                    "value": "value-2",
                }
            ]
        },
        {
            "key": "key 2",
            "values": [
                {
                    "value": "value-3"
                }
            ]
        }

代替

{
    key1:[1,2],
    key2:[3,4,5]
}

因此,我要转换此数组:

[
    {
        "login": "Affiliate 1",
        "referrals": [
            {
                "login": "referral-1",
                "bonusAmount": 100.00
            },
            {
                "login": "referral-2",
            }
        ]
    },
    {
        "login": "Affiliate 2",
        "referrals": [
            {
                "login": "referral-3",
                "bonusAmount": 300.00
            }
        ]
    },
    {
        "login": "Affiliate 3",
        "referrals": [
            {}
        ]
    }
]

到表格:

<table border="1">
  <tr>
    <th scope="col">Affiliate name</th>
    <th scope="col">Referral name</th>
    <th scope="col">Affiliate bonus</th>
  </tr>
  <tr>
    <td rowspan="2">Affiliate 1</td>
    <td>referral-1</td>
    <td>$100.00</td>
  </tr>
  <tr>
    <td>referral-2</td>
    <td></td>
  </tr>
  <tr>
    <td>Affiliate 2</td>
    <td>referral-3</td>
    <td>$300.00</td>
  </tr>
  <tr>
    <td>Affiliate 3</td>
    <td></td>
    <td></td>
  </tr>
</table>

1 个答案:

答案 0 :(得分:3)

一个选择是将主循环放在表ng-repeat="item in items"的tbody元素上,然后在每个tr ng-repeat="ref in item.referrals"上使用嵌套循环,将行跨度条件放在第一个td {{1 }}。

这是一个可行的例子

<td ng-if="$index == 0" rowspan={{item.referrals.length}}>{{item.login}}</td>
var app = angular.module('app', []);
app.controller('ctrl', function ($scope) {
   $scope.items = [
    {
        "login": "Affiliate 1",
        "referrals": [
            {
                "login": "referral-1",
                "bonusAmount": 100.00
            },
            {
                "login": "referral-2",
            }
        ]
    },
    {
        "login": "Affiliate 2",
        "referrals": [
            {
                "login": "referral-3",
                "bonusAmount": 300.00
            }
        ]
    },
    {
        "login": "Affiliate 3",
        "referrals": [
            {}
        ]
    }
  ];
  
});