Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

How can I iterate over this JSON values with AngularJS ng-repeat?

{
    "timestamp": "Wed Apr 02 2014, 19:03:19",
    "test": [
        441.02,
        null,
        null,
        460.99,
        485.91,
        501,
        null,
        null,
        null,
        null
    ],
    "test1": [
        437,
        null,
        null,
        464.989,
        488.52,
        499.996,
        null,
        null,
        null,
        null
    ],
    "test3": [
        10.85,
        null,
        null,
        10.9,
        10.9,
        10.9,
        null,
        null,
        null,
        null
    ]
}

And this is the controller Im using:

var myJson = angular.module('myJson', []);

function PostsCtrlAjax($scope, $http)
{

$http({method: 'POST', url: 'graphs.json'}).success(function(data)

    {
        $scope.values = data; // response data
    });


}

I wanna show all the values in test/1/2/3 in some html bootstrap table.

And also, how can I store all those values in some array[] with JavaScript? Thanks in advance!

share|improve this question
    
Could you please give the approximate layout you want to have. –  Kate Apr 6 at 5:26

1 Answer 1

up vote 0 down vote accepted

Here is what you need:

HTML

<table class="table" ng-controller="PostsCtrlAjax">
  <tr ng-repeat="key in keys">
    <td>{{key}}</td>
    <td ng-repeat="value in values[key] track by $index">{{value}}<td>
  </tr>
</table>

Since your tests arrays contain duplicate items (nulls), you should add track by $index to internal loop. It is recommended way to avoid duplicates issue.

JavaScript

angular.module('myJson', []).
  controller('PostsCtrlAjax', ['$scope', '$http', function($scope, $http) {
    $http({
      method: 'GET',
      url: 'graphs.json'
    }).success(function(data) {
        // Form array of test names for external ng-repeat that will render rows
        // Take only the properties that represent tests (filter out timestamp property)
        $scope.keys = Object.keys(data).filter(function(value) {
          return value.indexOf('test') === 0;
        })
        // Place data to scope in order to render cells in internal ng-repeat
        $scope.values = data; // response data
    });
  }]);

Plunker: http://plnkr.co/edit/yKj0QzowkIfNKDO1ECnJ?p=preview

share|improve this answer
    
Thank you so much :D - Solved –  mdv Apr 6 at 17:34

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.