用动态填充html中的json数据

时间:2016-02-23 19:00:52

标签: javascript html arrays angularjs json

我想使用AngularJS从json文件中填充表格。

json文件可能会不时变化(动态数据)。

要求是:通过解析view.html文件在html中填写表格。 表位于view.js文件中,AngularJS代码应位于{ "result": { "services": [ { "id": 1, "name": "My UI for some project that I'm doing that won't fit", "application": "app", "message": "application", "status": 1 }, { "id": 2, "name": "My DB for some project that I'm doing", "application": "app1", "message": "application1", "status": 3 }, { "id": 3, "name": "Another service", "application": "app2", "message": "application2", "status": 3 } ], } }

JSON文件:(服务树下可能还有更多的id)

{{1}}

输出表应如下所示:

enter image description here

PS:应该将表格对齐设置为名称值可能有或没有更多信息。

由于

1 个答案:

答案 0 :(得分:2)

虽然像@Johannes Jander说的那样, Stackoverflow不是"为我编写代码"服务我将告诉你如何做到这一点。

如果你不介意列的顺序不同,你可以轻松地迭代抛出对象的属性,你不需要操纵json对象。如果订单很重要,请告诉我,我会帮你解决。

要详细了解我们的内容,请点击以下链接:

  1. ng-repeat docs。
  2. How can I iterate over the keys, value in ng-repeat in angular
  3. 现在,代码:

    
    
    angular.module('app', []).
    controller('ctrl', function($scope) {
      $scope.json = {
        "result": {
          "services": [
            {
              "id": 1,
              "name": "My UI for some project that I'm doing that won't fit",
              "application": "app",
              "message": "application",
              "status": 1
            },
            {
              "id": 2,
              "name": "My DB for some project that I'm doing",
              "application": "app1",
              "message": "application1",
              "status": 3
            },
            {
              "id": 3,
              "name": "Another service",
              "application": "app2",
              "message": "application2",
              "status": 3
            }
          ],
        }
      }  
    });
    
    table {
      border-collapse: collapse;
    }
    
    td {
      border: 1px solid;
    }
    
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    
    <div data-ng-app="app" data-ng-controller="ctrl">
      <table data-ng-if="json.result.services.length > 0">
        <thead>
          <tr>
            <th data-ng-repeat="(key, value) in json.result.services[0]" data-ng-bind="key"></th>
          </tr>
        </thead>
        <tbody>
          <tr data-ng-repeat="service in json.result.services">
            <td data-ng-repeat="(key, value) in service" data-ng-bind="value"></td>
          </tr>
        </tbody>
      </table>
    </div>
    &#13;
    &#13;
    &#13;