EnigmaRM EnigmaRM - 1 month ago 7
AngularJS Question

How to ng-repeat into html table with multiple levels of json?

I have an object of social media stats. I'm trying to ng-repeat them into a table. Here's my plunker.

HTML:

<table>
<tr ng-repeat="(metric, metricData) in data">
<td>{{metric}}</td>
<td>{{metricData}}</td>
</tr>
</table>


Controller object:

$scope.data = { buzz:0,
Delicious:121,
Facebook:
{
like_count: "6266",
share_count: "20746"
},
GooglePlusOne:429,
LinkedIn:820,
Twitter:4074
};


I run into a problem when I get to the Facebook results. Within the
<td>
that entire object gets displayed (as it should be with how I have my code setup). But what I'd rather have happen is to repeat through that object and display the key and value in the cell.

I tried doing something looking to see if
metricData
is an object and doing some sort of ng-repeat on that. But I wasn't having luck with that. Any idea on how I can display the inner object (keys & value) within the cells?

Answer Source

You can define a scope function returning the type of metricData :

  $scope.typeOf = function(input) {
    return typeof input;
  }

And then you can display it according to its type :

  <tr ng-repeat="(metric, metricData) in data">
    <td>{{metric}}</td>
    <td ng-switch on="typeOf(metricData)">
      <div ng-switch-when="object">
        <div ng-repeat="(key, value) in metricData">
          <span>{{key}}</span>
          <span>{{value}}</span>
        </div>
      </div> 
      <span ng-switch-default>{{metricData}}</span>  
    </td>
  </tr>

You can see it in this Plunker