2015-10-28 106 views
1

我想从JSON渲染表格。键应该是TH标签和它下面的TD-tad的值。我设法以相反方式呈现表格:在angularjs中渲染表格

<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> 

但是如何以相反的方式做到这一点?

jsfiddle

回答

2

您需要为标题一次遍历键,然后遍历该行的值。

<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> 

更新jsfiddle

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> 
+0

我忘了说表格的内容是动态的,所以这个解决方案没有用处 –