Reputation: 524
So I have a List that I am returning from rest service. Now, I want to display this object in column format and now in row one. So it would be something like this:
firstName: Bob Alice
LastName: Doe Joe
EmailId: [email protected] [email protected]
ContactNo: 123123 12444
So how can I use ng-repeat over here:
<tr>
<th>firstName:</th>
<td>('Name should be displayed here')</td>
</tr>
Upvotes: 5
Views: 17013
Reputation: 229
If you declare the keys of the objects you're iterating through, you can nest your ng-repeats
so that you don't need to declare each row over and over. Do the following and nest them instead:
In the Angular App:
/*for the data*/
var personKeys = ['firstName', 'LastName', 'EmailID', 'ContactNo'];
var people = [
{
firstName: 'Bob',
LastName: 'Doe',
EmailID: '[email protected]',
ContactNo: 123123
},
/* etc */
];
/*don't forget to reference this in your controller with something like: */
this.pKeys = personKeys;
this.people = people;
In your HTML:
<table ng-controller='MyController as personList'>
<tr ng-repeat='key in personList.pKeys'>
<th>{{key}}</th>
<td ng-repeat='person in personList.people'>
{{person[key]}}
</td>
</tr>
</table>
This still has the problem of iterating over each person |attributes| times, instead of just once. I'm sure there is a clever way to only iterate once, memoize, and draw up the table without having to go through your entire data set many times, so that the runtime doesn't grow so quickly as you expand your data.
Upvotes: 1
Reputation: 1565
You can use ng-repeat on the td element.
<tr>
<th>firstName:</th>
<td ng-repeat="person in people">{{person.firstName}}</td>
</tr>
<tr>
<td ng-repeat="person in people">{{person.lastName}}</td>
</tr>
Upvotes: 14