在对象的嵌套数组上使用ng-repeat

时间:2018-10-15 18:26:16

标签: angularjs angularjs-ng-repeat

下面是我的JSON对象,我试图在html表中显示该对象。

$scope.results = {
  "data": [
    {
      "name": "Sam",
      "details": [
        {
          "official": [
            {
              "address1": "Link road",
              "pincode": 76755554
            },
            {
              "address1": "K main road",
              "pincode": 9766565
            }
          ]
        },
        {
          "name": "John",
          "details": [
            {
              "official": [
                {
                  "address1": "Old college road",
                  "pincode": 11111
                },
                {
                  "address1": "near east side",
                  "pincode": 6555446
                }
              ]
            }
          ]
        }
      ]
    }
  ]
}

我已经使用ng-repeat实现以下输出。但是我没有得到预期的结果 Final output table

这是我尝试过并卡住的代码JSFIDDLE

任何有关如何达到预期效果的想法都会很有帮助。

1 个答案:

答案 0 :(得分:0)

如果在具有更高级别时数据结构可能变得更加复杂,则可能必须稍作调整,但这应该重新格式化数据并将所有内容平整化为一组没有所有不同级别的人员。

$scope.peopleFlat = [];

function flattenPeople(people) {
    people.forEach((person) => {
        $scope.peopleFlat.push({
           name: person.name,
           addresses: person.details[0].official
        });

        if (person.details.length > 1) {
            flattenPeople([person.details[1]]);
        }
    });
}

flattenPeople($scope.people);

然后,您可以结合使用ng-repeat-startng-repeat-end来使其使用rowspan而不是嵌套的<table>元素来工作。

<table class="table table-bordered table-condensed">
    <tr>
        <th>Name</th>
        <th>Address</th>
        <th>Pincode</th>
    </tr>
    <tr ng-repeat-start="person in peopleFlat">
        <td rowspan="{{person.addresses.length || 1}}">{{person.name}}</td>
        <td>{{person.addresses.length ? person.addresses[0].address1 : ''}}</td>
        <td>{{person.addresses.length ? person.addresses[0].pincode : ''}}</td>
    </tr>
    <tr ng-repeat-end ng-repeat="address in person.addresses.slice(1)">
        <td>{{address.address1}}</td>
        <td>{{address.pincode}}</td>
    </tr>
</table>