1

I want to render tables out of JSONs. The keys should be the TH-tag and the value the TD-tad under it. I managed to render the tables the other way around:

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope){
    $scope.init = function(){
        $scope.json = {
            "entities":{"bezeichnung":"Basis","name":"Basis","id":16},
            "entities2":{"bezeichnung":"Basis2","name":"Basis2","id":17}
        }   
    }

});
</script>

<div ng-app="myApp" ng-controller="myCtrl" ng-init="init()">
    <div ng-repeat="(key,value) in json">
        <table border="1">
            <tr ng-repeat="(k,val) in value"><td>{{k}}</td><td>{{val}}</td></tr>
        </table>    
    </div>
</div>

But how to do it the other way around?

jsfiddle

2 Answers 2

2

You need to iterate over the keys once for the headings, then iterate over the values for the row.

<div ng-app="myApp" ng-controller="myCtrl" ng-init="init()">
  <div ng-repeat="(key, table) in json">
    <table border="1">
      <thead>
        <tr>
          <th ng-repeat="(key, _) in table">{{key}}</th> 
        </tr>
      </thead>
      <tbody>
        <tr>
          <td ng-repeat="(_, value) in table">{{value}}</td>
        </tr>
      </tbody>
    </table>    
  </div>
</div>

Updated jsfiddle.

Sign up to request clarification or add additional context in comments.

Comments

0
you also do like this

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script src="Scripts/angular.js"></script>
    <script>
        var app = angular.module('myApp',[]);
        app.controller('MyCtrl', function ($scope) {

            $scope.json = [
                  { "bezeichnung": "Basis", "name": "Basis", "id": 16 },
                  { "bezeichnung": "Basis2", "name": "Basis2", "id": 17 }

            ]


        });
    </script>
</head>
<body ng-app="myApp" ng-controller="MyCtrl">
   <div>
       <table>
           <tr>
               <td>Index</td>
               <td>bezeichnung</td>
               <td>name</td>
               <td>Id</td>
           </tr>
           <tr ng-repeat="(key,value) in json">
               <td>{{key}}</td>
               <td>{{value.bezeichnung}}</td>
               <td>{{value.name}}</td>
               <td>{{value.id}}</td>
           </tr>
       </table>
   </div>
</body>
</html>

1 Comment

I forgot to say that the contents of the table are dynamic so this solution is not useful

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.