使用来自一个ng-repeat的值作为另一个ng-repeat的一部分

时间:2013-11-21 18:51:29

标签: javascript html angularjs

我正在尝试构建一个具有动态列数的表,并希望使用这些列标题来决定要显示的对象的哪些属性。下面是我想要做的,但它会抛出一个解析错误。有什么想法吗?

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

th array

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

2 个答案:

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

答案 1 :(得分: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>
相关问题