如何使用AngularJS的ngRepeat指令从嵌套的JSON对象动态生成HTML表?

时间:2015-05-11 11:53:54

标签: javascript jquery html json angularjs

我必须从嵌套对象中创建如下表。

JSON对象:

{
    "A":{
        "1":"X",
        "2":"Y",
        "3":"Z"
    },
    "B":{
        "1":"P",
        "2":"Q",
        "3":"R"
    }
}

所需表:

A: X|Y|Z
B: P|Q|R

HTML code:

    <!DOCTYPE html>
<html data-ng-app="myApp">
<body>

    <div ng-controller="GreetingController" >
        <div ng-repeat='(key,val) in arr'>{{temp(val)}} 
            <div ng-repeat='(nestedKey,nestedVal) in aux'>  
                {{nestedVal}}
            </div>
        </div>
    </div>
</body>

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
    var myApp = angular.module('myApp',[]);
    myApp.controller('GreetingController', ['$scope', function($scope) {
        $scope.arr={"A":{"1":"X","2":"Y","3",},"B":{"1":"P","2":"Q"}};
        $scope.temp = function(val)
        {
            console.log(val);
            $scope.aux = val;
        }
    }]);
</script>

我无法理解<table><tr><td>标记的放置方式和位置,以便能够按照描述生成表格。

2 个答案:

答案 0 :(得分:2)

编辑:

tr是行,td是表格单元格

<html data-ng-app="myApp">
<body>
    <div ng-controller="GreetingController" >
        <table>
            <tr ng-repeat='(key,val) in arr'>
                <td>
                    {{key}} 
                </td>
                <td ng-repeat='(nestedKey,nestedVal) in val'>  
                    {{nestedVal}}
                </td>
            </tr>
        </table>
    </div>
</body>

答案 1 :(得分:-1)

<div ng-controller="GreetingController" >
   <table>   
      <tr>
          <td><div ng-repeat='(key,val) in arr'>{{temp(val)}} </td>
      </tr>
      <tr><td> <div ng-repeat='(nestedKey,nestedVal) in aux'> </td> 
                 {{nestedVal}}
             </div>
      </tr>
        </div>
  </table>
 </div>