如何使用AngularJS创建嵌套表?

时间:2016-03-14 08:40:26

标签: javascript angularjs

我想在表格中显示JSON响应数据。架构未提前知道,JSON最多只能包含一个嵌套对象。 此示例显示一个表,显示键值对:

function TestController($scope) {
  $scope.data = {
    a: 42,
    b: "test",
    c: {
      x: -1,
      y: 1
    }
  };

  $scope.getTypeOf = function(obj) {
    return typeof obj;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<table ng-app="" ng-controller="TestController" border="1">
  <tr ng-repeat="(key, value) in data">
    <td>{{key}}</td>
    <td ng-switch on="getTypeOf(value)">
      <div ng-switch-when="object">
        obj: {{value}}
      </div>
      <div ng-switch-default>{{value}}</div>
    </td>
  </tr>
</table>

现在,对于属性“c”,我想创建一个这样的嵌套表:

function TestController($scope) {
  $scope.data = {
    a: 42,
    b: "test",
    c: {
      x: -1,
      y: 1
    }
  };

  $scope.getTypeOf = function(obj) {
    return typeof obj;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<table ng-app="" ng-controller="TestController" border="1">
  <tr ng-repeat="(key, value) in data">
    <td>{{key}}</td>
    <td ng-switch on="getTypeOf(value)">
      <div ng-switch-when="object">
        <tr ng-repeat="(key1, value1) in value">
          <td>{{key1}}</td>
          <td>{{value1}}</td>
        </tr>
      </div>
      <div ng-switch-default>{{value}}</div>
    </td>
  </tr>
</table>
直觉上这应该可行,但它会在Chrome中引发Error: $compile:ctreq Missing Required Controller。我怎样才能达到正确的行为?

3 个答案:

答案 0 :(得分:1)

试试这个。

function TestController($scope) {
  $scope.data = {
    a: 42,
    b: "test",
    c: {
      x: -1,
      y: 1
    }
  };

  $scope.getTypeOf = function(obj) {

    return typeof obj;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<table ng-app="" ng-controller="TestController" border="1">
  <tr ng-repeat="(key, value) in data">
    <td>{{key}}</td>
    <td ng-switch on="getTypeOf(value)">
      <table ng-switch-when="object"  border="1">
        <tr ng-repeat="(key1, value1) in value">
          <td >{{key1}}</td>
          <td >{{value1}}</td>
        </tr>
      </table>
      <div ng-switch-default>{{value}}</div>
    </td>
  </tr>
</table>

答案 1 :(得分:0)

您定义控制器的方式是错误的。

你需要像

这样的东西
angular.module('app').controller("TestController", ['$scope', 
  function($scope){ 
    // your controller code 
  }
]);

答案 2 :(得分:0)

value上的ng-switch-when="object"是数组的对象。您需要使用Object.keys来提取对象键,然后您可以阅读其中的每一个并构建您的key value