2015-10-07 40 views
0

我有以下使用ng-repeat访问的JSON对象。我在第一列中获得了所有名称,而不是分组到不同的列中。如何使用ng-repeat正确访问嵌套元素?

$scope.tableItems = [ 
{ 
    "title": "BUILDING ID", 
    "subtitle": [ 
    { 
     "name": "Nexon" 
    }, 
    { 
     "name": "Kodak" 
    }, 
    { 
     "name": "Lion" 
    } 
    ] 
}, 
{ 
    "title": "TECHNOLOGY", 
    "subtitle": [ 
    { 
     "name": "Robotic" 
    }, 
    { 
     "name": "AI" 
    }, 
    { 
     "name": "Algorithm" 
    ] 
} 

]; 

我试图访问它像这样用玉,

table 
     thead 
      tr 
       th(ng-repeat = "x in tableItems") {{ x.title }} //- get BUILDING ID and TECHNOLOGY 
     tbody(ng-repeat = "x in tableItems") //- get all the NAMEs 
      tr(ng-repeat = "(key, value) in x.subtitle") 
       td {{ value.name }} 

并且将结果返回

BUILDING ID     TECHNOLOGY 

Nexon 

Kodak 

Lion 

Robotic 

AI 

Algorithm 

我希望它能够根据表头打印表,所以根据

“建筑物ID”将只有3项(Nexon,柯达和狮子)和“技术”

会有(机器人,AI和算法)。我的代码缺少什么?

回答

1

您需要“转置”您的数据以形成表格网格。目前,当使用ng-repeat生成表格单元格时,您的数据更适合按每列布置多行而不是每行多列。

提取标题,并修改每行合并所有列:

$scope.tableHeadings = _.pluck($scope.tableItems, "title"); 
    var T = {}; 
    _.each($scope.tableItems, function (item, colind) { 
     _.each(item.subtitle, function (row, rowind) { 
      if (!_.has(T, 'r' + rowind)) { 
       T['r' + rowind] = []; 
      } 
      T['r' + rowind].push({ 
       "name": row.name 
      }); 
     }); 
    }); 

    $scope.tableRows = T; 

在HTML然后使用它是这样的:

<table> 
    <thead> 
     <th ng-repeat="heading in tableHeadings">{{heading}}</th> 
    </thead> 
    <tbody> 
     <tr ng-repeat="(key, columns) in tableRows"> 
      <td ng-repeat="col in columns">{{col.name}}</td> 
     </tr> 
    </tbody> 
</table> 

看到它在行动here。我在这里使用了Lodash图书馆,但是你可以不用它。