AngularJS ng-repeat 从数组填充网格 [英] AngularJS ng-repeat to populate grid from array
问题描述
提前感谢您的阅读.我正在尝试利用 angular 的 ng-repeat 将对象从数组渲染到 Nx3 表中.为了举例,让我们考虑一个 3x3 的表.
Thanks in advance for reading. I am trying to utilize angular's ng-repeat to render objects from an array into an Nx3 Table. For the sake of example let's consider a 3x3 table.
以下是数组的简化示例:
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:
The "text" field describes where in the 3x3 grid matrix each element should appear. I would like to use ng-repeat on objects to generate html that looks like this:
<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>
有没有什么方法可以在不需要将数组分解为每一行的单独数组的情况下实现这一点?
推荐答案
最好的方法是改变控制器中的视图模型并将其绑定到 ng-repeat(但你已经说过你不想这样做).如果你打算走那条路,你也可以看看用户 @m59 answer 在那里他创建了一个可重复使用的过滤器来做到这一点.然而,这只是一个简单的答案,利用内置过滤器的可配置评估表达式,我们可以在其中返回真/假值以确定它们是否需要重复.这最终的唯一优点是不需要创建 2 个 ng-repeat 块(但这还不错).所以在你的控制器中添加一个作用域函数,
Best possibly way would be to alter your view model in the controller and bind that to ng-repeat (But you already said you do not want to do that). If you ever plan to take that route you can also take a look at user @m59 answer where he creates a reusable filter to do it. However this is just a simple answer making use of built in filter's configurable evaluation expression where we can return truthy/falsy value to determine if they need to be repeated or not. This eventually has the only advantage of no need to create 2 ng-repeat blocks (But that is not so bad though). So in your controller add a function on the scope,
$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);
}
并在您的视图中应用过滤器:
and in your view apply the filter:
<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>
这篇关于AngularJS ng-repeat 从数组填充网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!