0

I have a REST service that returns me a JSON data similar to the below format:

{
    "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"
        }
    ]
}

How should I parse this result and populate a table which would look similar to the image below:

enter image description here

http://jsfiddle.net/p7yLztwg/

2 Answers 2

4

Try this one 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>

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. ng-repeat-start/ng-repeat-end solution seems neat. But Iam not sure about performance of this solution compared to @wander-nauta
I don't see any big performance impact between those two approaches, you man test on bigger data like 100K rows...
3

You could try something like this:

<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>

This creates a tbody for every continent, and a tr for every country. Only the first row of a continent gets a cell for the name of that continent. That cell also gets a rowspan attribute so that it spans multiple rows.

Demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.