Parshuram Parshuram - 8 days ago 7
AngularJS Question

Dynamic ng-repeat in AngularJS

My angular controller is

$scope.dyna = [
{ "name": "parshuram", "age": 24 },
{ "name": "Tejash", "age": 26 },
{ "name": "Vinayak", "age": 25 }
];


My html

<table>
<tbody>
<tr ng-repeat="test in dyna">
<td>{{test.name}}</td>
<td>{{test.age}}</td>
</tr>
</tboody>
</table>


This works correctly, and outputs

Parshuram 24
Tejash 26


But if an another variable is added to my scope variable, I need to make changes in my html table:

$scope.dyna = [
{ "name": "parshuram", "age": 24 ,"void": true},
{ "name": "Tejash", "age": 26,"void" : false }
];

<table>
<tbody>
<tr ng-repeat= "test in dyna">
<td>{{test.name}}</td>
<td>{{test.age}}</td>

<!-- I don't want to have to add this, the columns should be added dynamically -->
<td>{{test.void}}</td>
</tr>
</tboody>
</table>


In that case, can the columns be generated dynamically, for example by getting all my object variables from the scope?

Answer

ng-repeat can loop over object key/values as well:

<table>
  <tbody>
    <tr ng-repeat= "test in dyna">
      <td ng-repeat="(key, value) in test">
        {{value}}
      </td>
     </tr>
  </tbody>
</table>

However as noted in the docs linked above, there are a few limitations compared to an ng-repeat that works on arrays:

  • The JavaScript specification does not define the order of keys returned for an object, so Angular relies on the order returned by the browser when running for key in myObj. Browsers generally follow the strategy of providing keys in the order in which they were defined, although there are exceptions when keys are deleted and reinstated. See the MDN page on delete for more info.

  • ngRepeat will silently ignore object keys starting with $, because it's a prefix used by Angular for public ($) and private ($$) properties.

  • The built-in filters orderBy and filter do not work with objects, and will throw an error if used with one.

Comments