如何使用数组迭代JSON对象并使用Angular JS填充表

时间:2016-11-02 17:57:47

标签: javascript angularjs json

我有一个REST服务,它返回一个类似于以下格式的JSON数据:

{
    "Africa" : [{
            "country" : "Nigeria",
            "capital" : "Abuja"
        }, {
            "country" : "Kenya",
            "capital" : "Nairobi"
        }, {
            "country" : "Ghana",
            "capital" : "Accra"
        }
    ],
    "Asia" : [{
            "country" : "India",
            "capital" : "New Delhi"
        }, {
            "country" : "China",
            "capital" : "Beijing"
        }
    ],
    "Europe" : [{
            "country" : "France",
            "capital" : "Paris"
        }
    ]
}

我应如何解析此结果并填充一个与下图类似的表格:

enter image description here

http://jsfiddle.net/p7yLztwg/

2 个答案:

答案 0 :(得分:4)

试试这个Fiddle

<table ng-app="testApp" ng-controller="testController">
<tr>
  <td>Contitent</td>
  <td>Country</td>
  <td>Capital</td>
</tr>
<tr ng-repeat-start="(key, val) in testData">
    <td rowspan="{{val.length}}">{{key}}</td>
    <td>{{val[0].country}}</td>
    <td>{{val[0].capital}}</td>
</tr>
<tr ng-repeat-end ng-repeat="value in val.slice(1)">
    <td>{{value.country}}</td>
    <td>{{value.capital}}</td>
</tr>

答案 1 :(得分:3)

您可以尝试这样的事情:

<table>
  <thead>
    <tr>
      <th>Continent</th>
      <th>Country</th>
      <th>Capital</th>
    </tr>
  </thead>
  <tbody ng-repeat="(continent, countries) in yourjsondata">
    <tr ng-repeat="country in countries">
      <td ng-if="$first" rowspan={{countries.length}}>{{ continent }}</td>
      <td>{{ country.country }}</td>
      <td>{{ country.capital }}</td>
    </tr>
  </tbody>
</table>

这为每个大陆创建tbody,为每个国家/地区创建tr。只有一个大陆的第一行才能获得该大陆名称的单元格。该单元格还获得rowspan属性,以便它跨越多行。

Demo