从JSON创建一个HTML表

Create a HTML table from JSON

本文关键字:一个 HTML JSON 创建      更新时间:2024-01-05

我有一个rails应用程序,我正在将其转换为angularjs。

从剩下的API中,我得到了类似JSON的:

[{"id":1,"products":{"type":"Mustang","color":"blue"},"created_at":"2013-12-02T01:05:20.956Z","updated_at":"2013-12-02T01:05:20.956Z"}]

我的angular现在只是在JSON中循环,并打印出整个数据列:

<tr ng-repeat="row in rows">
    <td><a href='#'>THIS IS -> </a>{{row.data}}</td>
</tr>

基本上,我想从数据列、键和值中提取数据,并在此基础上创建一个HTML表。问题是数据可能会有所不同,所以不总是像"type:Mustang"这样的键/值是第一个,有时值会为空,但键不会。

不久前我问了一个类似的问题,得到了一个绝妙的答案。解决方案2非常适合Ruby,但我想为我的项目将其转换为angularjs。

谢谢你的帮助!

要以AngularJS的方式转换Ruby解决方案,您可以使用像UndercoreJS这样的第三方库来根据需要转换JSON。

因此,您可以首先从您的其余API响应中检索产品列表:

var rows = [{"id":1,"products":{"type":"Mustang","color":"blue"},"created_at":"2013-12-02T01:05:20.956Z","updated_at":"2013-12-02T01:05:20.956Z"}, ...]
$scope.products = _.pluck(rows, 'products'); // make a list of the products property of each row

然后,你可以计算你的标题:

$scope.headers = _.chain($scope.products)
                  .map(_.keys) // take the keys of each product
                  .reduce(function(a, b) {
                            return _.union(a, b);
                          }, []) // merge all keys without double
                  .value();

最后,您可以通过迭代标题和产品来显示您的表:

<table>
  <tbody>
    <tr>
      <th ng-repeat="key in headers">{{ key }}</th>
    </tr>
    <tr ng-repeat="product in products">
      <td ng-repeat="key in headers">{{ product[key] }}</td>
    </tr>
  </tbody>
</table>

如果一个产品没有给定的密钥,那么它将不会显示任何内容。

看看这个笨蛋。

像Underscore这样的实用程序库非常方便以函数方式操作数据。我建议您查阅API和文档。

您可以将其设置为一个指令来代替ng repeat(这只是一个指令),并遵循Ruby代码中的逻辑。

您可以使用ng repeat,并使用以row.data为参数的函数来代替{{row.data}}。然后,该函数可以处理对键/值的必要检查。

Darryl