【问题标题】:JSON + AngularJSJSON + AngularJS
【发布时间】:2014-04-06 05:11:05
【问题描述】:

如何使用 AngularJS ng-repeat 迭代这个 JSON 值?

{
    "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
    ]
}

这是我正在使用的控制器:

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

function PostsCtrlAjax($scope, $http)
{

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

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


}

我想在一些 html 引导表中显示 test/1/2/3 中的所有值。

另外,我如何使用 JavaScript 将所有这些值存储在某个数组 [] 中? 提前致谢!

【问题讨论】:

  • 能否请您给出您想要的大致布局。

标签: json angularjs ng-repeat


【解决方案1】:

这是你需要的:

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>

由于您的测试数组包含重复项(空值),您应该将track by $index 添加到内部循环中。这是recommended 避免重复问题的方法。

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

【讨论】:

  • 非常感谢 :D - 已解决
猜你喜欢
  • 2015-06-29
  • 1970-01-01
  • 2017-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多