DaveC426913
DaveC426913

Reputation: 2046

using Angular ng-repeat to display JSON rows/columns

The JSON I am getting back from the API is nested FIRST by field (i.e. table columns), THEN by record(i.e. table rows). So, the JSON looks like this:

myJSON = {
    'data':{
        'id': [1,2,3],
        'groks':['a','b','c']
    }
}

I'm trying to use angular to display them correctly in my table. This is how they're supposed to look:

id groks
 1   a
 2   b
 3   c

It's not as simple as

<tbody ng-repeat="x in myJSON.data">
    <tr>
        <td>{{x[0]}}</td>
        <td>{{x[1]}}</td>
    </tr>
</tbody>

Because I'll end up with this, or somesuch:

id groks
 a   b  
 1   2

So, how do I tell the ng-repeat to FIRST iterate through the inner rows, THEN through the outer columns?

The long way is to pre-manipulate the JSON into a format that can be iterated. i.e. I need to manipulate the data until it looks like this:

myJSON = {
    'data':{
        ['id': 1,'groks':'a'],
        ['id': 2,'groks':'b'],
        ['id': 3,'groks':'c']
    }
}

And then I can do this:

<tbody ng-repeat="x in myJSON.data">
    <tr>
        <td>{{x.id}}</td>
        <td>{{x.groks}}</td>
    </tr>
</tbody>

But do I have any alternate options?

Upvotes: 0

Views: 1577

Answers (1)

rob
rob

Reputation: 18513

You can just iterate over one of the arrays and use $index to get the corresponding elements in any other arrays:

<tbody ng-repeat="id in myJSON.data.id">
    <tr>
        <td>{{id}}</td>
        <td>{{myJSON.data.gorks[$index]}}</td>
    </tr>
</tbody>

Upvotes: 1

Related Questions