0

I'm trying to implement a table using ng-repeat for the following data :

    [{
    "Name": "Alfreds Futterkiste",
    "City": "Berlin",
    "Country": "Germany"
}, {
    "Name": "Berglunds snabbköp",
    "City": "Luleå",
    "Country": "Sweden"
}]

Here is my AngularJS code :

<table>
    <tr ng-repeat="d in stuff">
        <td>
            {{d.Name}}    
        </td>
        <td>
            {{d.Country}}
        </td>
        <td>
            {{d.City}}
        </td>
    </tr>
</table>

The above code works fine but the number of td has been hard coded. Is there any way to make it dynamic.

1
  • use angular template? http://www.jptacek.com/2014/02/angularJS-templates/ Not as elegant a solution as Simon has proposed, but would be a possibility for a variety of mixed data content. Commented Jan 5, 2015 at 11:17

1 Answer 1

2

Add a second ng-repeat to your table:

<table>
    <tr ng-repeat="d in stuff">
        <td ng-repeat="(key, value) in d">
            {{value}}    
        </td>
    </tr>
</table>

Its worth noting this will only be valid markup if all results in d are equal in length.

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

8 Comments

this is change the order of the column, because of angular will sort the object field according to key.
if you want a custom order you can use angulars orderBy in your ng-repeat... docs.angularjs.org/api/ng/filter/orderBy
orderBy do not change the order of the columns instead it will order the table rows.
Use it in the second ng-repeat so the <td></td> is ordered.
using orderBy will re-order the data apear in the table it will not change the order of the columns
|

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.