我想在表格中显示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>
答案 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
表