提前感谢您的阅读。我正在尝试利用 Angular 的 ng-repeat 将数组中的对象渲染到 Nx3 表中。为了举例,让我们考虑一个 3x3 的表格。
下面是数组的简化示例:
objects = [{"text": "One, One"},{"text": "One, Two"},{"text": "One, Three"},
{"text": "Two, One"},{"text": "Two, Two"},{"text": "Two, Three"},
{"text": "Three, One"},{"text": "Three, Two"},{"text": "Three, Three"}];
“文本”字段描述了每个元素在 3x3 网格矩阵中应该出现的位置。我想在 objects 上使用 ng-repeat 来生成如下所示的 html:
<table>
<tr>
<td>One, One</td>
<td>One, Two</td>
<td>One, Three</td>
</tr>
<tr>
<td>Two, One</td>
<td>Two, Two</td>
<td>Two, Three</td>
</tr>
<tr>
<td>Three, One</td>
<td>Three, Two</td>
<td>Three, Three</td>
</tr>
</table>
有没有什么方法可以实现这一点而无需将数组分解为每一行的单独数组?
最佳答案
最好的方法是在 Controller 中更改您的 View 模型并将其绑定(bind)到 ng-repeat(但您已经说过您不想这样做)。如果你打算走那条路,你也可以看看用户 @m59 answer他创建了一个可重复使用的过滤器来做到这一点。然而,这只是一个简单的答案,利用内置过滤器的可配置评估表达式,我们可以在其中返回 truthy/falsy 值以确定它们是否需要重复。这最终具有不需要创建 2 个 ng-repeat block 的唯一优势(但这并不是那么糟糕)。因此,在您的 Controller 中,在作用域上添加一个函数,
$scope.getFiltered= function(obj, idx){
//Set a property on the item being repeated with its actual index
//return true only for every 1st item in 3 items
return !((obj._index = idx) % 3);
}
并在您的 View 中应用过滤器:
<tr ng-repeat="obj in objects | filter:getFiltered">
<!-- Current item, i.e first of every third item -->
<td>{{obj.text}}</td>
<!-- based on the _index property display the next 2 items (which have been already filtered out) -->
<td>{{objects[obj._index+1].text}}</td>
<td>{{objects[obj._index+2].text}}</td>
</tr>
关于arrays - AngularJS ng-repeat从数组填充网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28057513/