嵌套的ng-repeat与垂直表

时间:2016-06-16 06:04:10

标签: angularjs json angularjs-ng-repeat

我有一个包含x个数字元素的json数组,其中每个元素都是另一个json数组。我想使用嵌套的ng-repeat迭代这个数组,类似于nested ng-repeat

我的问题是我想在“垂直表”中执行此操作:

<!-- for the big json -->
<table ng-repeat = "obj in data "style="width:100%">
  <tr>
    <th>data01</th>
    <!--for thr first object in the big json -->
    <tr ng-repeat = "var in obj">{{var}}</tr>
  </tr>
  <tr>
    <!--for the second object in the big json -->
    <th>data02</th>
    <tr ng-repeat = "var in obj">{{var}}</tr>
  </tr>
</table>

数据

[ "data01":[{"firstName":"John", "lastName":"Doe"}], "data02":["{"firstName":"Anna", "lastName":"Smith"}], "data03":[{"firstName":"Peter","lastName":"Jones"}] ]

因此第一个ng-repeat将用于每个对象,第二个将将值赋予表格的“右侧”。

我找不到组织HTML元素的正确方法,因此它将按此顺序显示。这是example,我的意思是“垂直表”。

3 个答案:

答案 0 :(得分:2)

我不知道你为什么要为obj

迭代两次
<table ng-repeat = "(key,obj) in data "style="width:100%">
    <tr> 
      <th>{{key}}</th>
    </tr>
    <tr ng-repeat = "var in obj">          
        <td>{{var}}</td>
    </tr>
</table>

答案 1 :(得分:1)

为了让您的表格以您描述的格式显示信息,我们必须对您的数据做一些假设。值得注意的是,我们假设您的数组将始终以相同的顺序输出,并且只有每个数组中的第一个对象包含您为此表所关注的数据。如果您的数据顺序不同,或者您希望迭代的数组中有多个对象,那么您描述的格式将无法实现。

实际上,这种解决方案非常严格,如果数据以任何方式发生变化,它将会中断。这不是角度的正常设计;只要有可能,您应该尝试生成更接近您想要使用的信息的数据。

此解决方案使用数组访问和(key, value)迭代的组合来实现结果。

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

app.controller('MainCtrl', function($scope) {
  $scope.data = [{
    "data01": [{
      "firstName": "John",
      "lastName": "Doe"
    }],
    "data02": [{
      "firstName": "Anna",
      "lastName": "Smith"
    }],
    "data03": [{
      "firstName": "Peter",
      "lastName": "Jones"
    }]
  }];
});
<!DOCTYPE html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <link rel="stylesheet" href="style.css" />
  <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9"></script>
  <script src="app.js"></script>
</head>

<body ng-controller="MainCtrl">
  <table style="width:100%">
    <tr ng-repeat="(key,values) in data[0]">
      <th>{{key}}</th>
      <td ng-repeat="(key, value) in values[0]">{{value}}</td>
    </tr>
  </table>
</body>

</html>

答案 2 :(得分:1)

td 中使用 ng-repeat 而不是 tr 表。我遇到了同样的问题,最后设法在垂直表格中显示结果。

<div id="bdDiv" ng-controller="businessDate" ng-init="init()">
    <table>
        <tr >
            <th>Country</th>
            <td ng-repeat="item in response">{{item.type}}</td>
        </tr>
        <tr >
            <th>STAT</th>   
            <td ng-repeat="item in response">{{item.statDate}}</td>
        </tr>
        <tr >
            <th>OTP</th>    
            <td ng-repeat="item in response">{{item.otpDate}}</td>
        </tr>
        <tr >
            <th>LTP</th>
            <td ng-repeat="item in response">{{item.ltpDate}}</td>
        </tr>
    </table>
</div>
相关问题