2013-11-21 28 views
0

我正在嘗試構建一個包含動態列數的表,並希望使用這些列標題來決定要顯示哪個對象的屬性。以下是我想要做的事情,但它會拋出一個解析錯誤。有任何想法嗎?使用一個ng-repeat中的值作爲另一個ng-repeat的一部分

<table class="table"> 

    <thead> 
     <th ng-repeat="th in tableHeaders">{{th}}</th> 
    </thead> 

    <tr ng-repeat="item in items | filter:query | orderBy:orderProp"> 
     <td>{{item.{{th}}}}</td> 
    </tr> 

</table> 

個陣列

['column1', 'column2'] 

項數組

[ 
    {column1:blah, column2:blah}, 
    {column1:blah2, column2:blah2} 
] 

更新1 我嘗試使用以下,我得到一堆空行的。

<tr ng-repeat="item in items | filter:query | orderBy:orderProp"> 
<td ng-repeat="th in tableHeaders">{{item.$eval(th)}}</td> 
</tr> 
+0

你可以發佈樣本數據嗎?你想達到什麼目標? – Satpal

+0

'ng-repeat'創建它自己的子範圍,所以'th'不能在其他'repeat'中訪問,因爲它超出了範圍。 – tymeJV

+0

'th'變量只存在於它自己的'scope'中的'ng-repeat'塊中。在第二個ng-repeat中,你可以使用'tableHeaders [$ index]'而不是'th'。但是,正如我所看到的,您正試圖訪問項目的屬性,因此可能需要一個eval()? – Animator

回答

1

實施例。 Fiddle

<table class="table"> 
    <thead> 
     <th ng-repeat="th in tableHeaders">{{th}}</th> 
    </thead> 
    <tr ng-repeat="item in items"> 
     <td ng-repeat="col in tableHeaders">{{item[col]}}</td> 
    </tr> 
</table> 

如果您在tableHeaders列是一個對象,你也可以做col.property。​​

+0

完美答案! – zmanc

0

正如其他人在評論中指出的,ng-repeat創建自己的子範圍。所以試圖在表中稍後引用th是不可能的,除非它是父母。

所以你需要的是一個額外的ng-repeat。對你實際td元素。一個重複將處理<tr>,另一個將遍歷每個行中的對象數量。

退房使用從標題的列定義此fiddle for an example

<table class="table"> 

    <thead> 
     <th ng-repeat="th in tableHeaders">{{th}}</th> 
    </thead> 

    <tr ng-repeat="item in items"> 
     <td ng-repeat="col in item">{{col}}</td> 
    </tr> 

</table> 
+0

這將工作,如果他將有秩序的對象。這不會按列名工作。但也是一個很好的解決方案;)。如果這是他想要的陣列應該足夠。 – Animator

+0

越來越接近,但像@islander說,如果列在對象上的順序不同,那麼這是一個問題。另外,如果對象有額外的列,它們仍然顯示。 http://jsfiddle.net/npP6u/6/ – zmanc

相關問題