Niko Lang
Niko Lang

Reputation: 559

Render table in angularjs

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

Upvotes: 1

Views: 1234

Answers (2)

Ashokreddy
Ashokreddy

Reputation: 352

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>

Upvotes: 0

Dan Prince
Dan Prince

Reputation: 29989

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.

Upvotes: 2

Related Questions