AngularJS - 动态生成的JSON表,具有各种键名

时间:2018-05-27 12:03:58

标签: html angularjs json dynamic

我正在尝试使用动态生成的JSON创建表。 例如,JSON可以如下所示:

[{"date": "10-10-2010", "Cost":"10", "Column3": 20} ...]

但它也可能如下所示:

[{"date": "10-10-2010", "Column1":"ex", "Column2": 1, "Column4": "text"} ...]

我希望列的标题是JSON键的名称,并将行单元格作为这些键的值。 有没有简单的方法来实现这个目标?

2 个答案:

答案 0 :(得分:1)

对于标题,您需要获取第一行json数据,如下所示:

<thead>
   <tr>
     <th ng-repeat="(header, value) in jsonData[0]">
       {{header}}
     </th>
    </tr>
</thead>

之后你应该像这样迭代tbody:

 <tbody>
    <tr ng-repeat="rowData in jsonData">
      <td ng-repeat="cellData in rowData">
        {{cellData}}
      </td>
    </tr>
 </tbody>

这是绑定动态html表的最简单方法。

希望这对你有用!!

答案 1 :(得分:1)

你需要有关键的数组。我们假设我们有返回键的函数:

$scope.getKeys = function(obj) {
  return Object.getOwnPropertyNames(obj).slice(0, -1)
}

现在,假设在动态生成的JSON数组中(让我们称之为data),所有对象都具有相同的键(列),您可以按如下方式显示表:

<table>
  <thead>
    <tr>
      <th ng-repeat="key in getKeys(data[0])">
        {{key}}
      </th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="row in data">
      <td ng-repeat="col in getKeys(data[0])">{{row[col]}}</td>
    </tr>
  </tbody>
</table>

请参阅下面的示例data1data2的工作代码段。

&#13;
&#13;
var myApp = angular.module('myApp', []);

function MyCtrl($scope) {
  $scope.data1 = [{
      "date": "10-10-2010",
      "Column1": "ex",
      "Column2": 1,
      "Column4": "text"
    },
    {
      "date": "11-11-2011",
      "Column1": "ex",
      "Column2": 2,
      "Column4": "text"
    }
  ];

  $scope.data2 = [{
      "date": "10-10-2010",
      "Cost": "10",
      "Column3": 20
    },
    {
      "date": "10-10-2011",
      "Cost": "11",
      "Column3": 30
    }
  ]

  $scope.getKeys = function(obj) {
    return Object.getOwnPropertyNames(obj).slice(0, -1)
  }
}
&#13;
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td,
th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">

  <h4>For data1:</h4>
  <table>
    <thead>
      <tr>
        <th ng-repeat="key in getKeys(data1[0])">
          {{key}}
        </th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="row in data1">
        <td ng-repeat="col in getKeys(data1[0])">{{row[col]}}</td>
      </tr>
    </tbody>
  </table>

  <h4>For data2:</h4>
  <table>
    <thead>
      <tr>
        <th ng-repeat="key in getKeys(data2[0])">
          {{key}}
        </th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="row in data2">
        <td ng-repeat="col in getKeys(data2[0])">{{row[col]}}</td>
      </tr>
    </tbody>
  </table>

</div>
&#13;
&#13;
&#13;