在AngularJS中显示动态JSON

iCo*_*ode 3 json angularjs

从Web服务我得到一个JSON字符串.它可能会根据请求而有所不同.2个JSON结果是

结果1

[
  {
    "Key": 1,
    "ID": 1,
    "applicationId": "1",
    "applicationName": "APP1"
  },
  {
    "Key": 2,
    "ID": 1,
    "applicationId": "2",
    "applicationName": "APP2"
  }
]
Run Code Online (Sandbox Code Playgroud)

结果2

[
  {
    "OrgKey": 1,
    "ID": 1,
    "OrgID": "1",
    "OrgName": "Org1"
  },
  {
    "OrgKey": 2,
    "ID": 4,
    "OrgID": "6",
    "OrgName": "Org2"
  }
]
Run Code Online (Sandbox Code Playgroud)

我将如何在表格中显示?

在控制器js文件中我使用$http.get方法并在我放入的Success方法中

$scope.resultData = data;
Run Code Online (Sandbox Code Playgroud)

但在HTML中我将如何显示动态内容?

<table>
<thead>
  <tr>
    <th ng-repeat = "result in resultData">
     <!-- Not the right way -->
     <!-- Here I want to put the headers like "Key,ID" ... -->
    </th>
   </tr> </thead>
  <tbody>
  <tr ng-repeat = ""result in resultData">
   <td> {{result.Key }} </td>
   <!-- When the firlds vary, how to put? ->
  </tr>
  </tbody>
</table>
Run Code Online (Sandbox Code Playgroud)

可能吗?如果是这样如何?谢谢.

Poy*_*maz 10

首先,你应该得到第一行来设置你的表头像这样

<thead>
  <tr>
    <th ng-repeat="(header, value) in resultData[0]">
      {{header}}
    </th>
  </tr>
</thead>
Run Code Online (Sandbox Code Playgroud)

在此之后,tbody你应该首先得到你的行然后在行内所有细胞,

<tbody>
  <tr ng-repeat="row in resultData">
    <td ng-repeat="cell in row">
      {{cell}}
    </td>
  </tr>
</tbody>
Run Code Online (Sandbox Code Playgroud)

这是工作PLUNKER ...

UPDATE

一些用户询问是否可以在不排序标题及其值的情况下处理此问题...

答案是肯定的,但在开始之前你应该知道为什么它已经按字母顺序排序了......

angular ng-repeat指令与数组和对象的工作方式不同......如果使用数组,你可以对它进行排序,但这不是对象的选项,这里讨论它...

所以现在最好的方法是在我们在ng-repeat中使用它们之前将对象值推送到数组中.

这是第二个PlUNKER

注意:您将看到我从数组中删除$$ hashKey,因为它们不是原始元素的属性,angular会自动将它们添加到对象中以观察更改