在angularjs中呈现表格

时间:2015-10-28 12:45:56

标签: javascript angularjs

我想用JSON渲染表格。键应该是TH-tag和TD-tad下面的值。我设法反过来渲染表格:

<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 个答案:

答案 0 :(得分: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

答案 1 :(得分: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>