Reputation: 132
I want to display JSON response data in a table. Schema is not known in advance and JSON can contain at most one nested object. This example shows a table, which displays key-value pairs:
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>
Now, for the property "c", I want to create a nested table like this:
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>
Upvotes: 0
Views: 1262
Reputation: 17289
try this.
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>
Upvotes: 1
Reputation: 1689
The way you defined your controller is wrong.
You need something like
angular.module('app').controller("TestController", ['$scope',
function($scope){
// your controller code
}
]);
Upvotes: 0
Reputation: 2010
the value
on ng-switch-when="object"
is an object to array. you need to use Object.keys
to extract the object keys, and then you can read each one of them and build your key
value
table
Upvotes: 0