在此先感谢您阅读。我试图利用角的的 NG-重复的渲染从数组对象到一个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的网格矩阵的每个元素应该出现在那里。我想上的对象的生成html,看起来像这样用NG-重复:
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-重复(但是你已经说过你不希望这样做) 。如果你打算采取这条路线,您还可以看看用户@m59回答他在那里创建了一个可重复使用的过滤器来做到这一点。然而,这仅仅是一个简单的答案,利用内置过滤器的配置评估前pression在这里我们可以回到truthy / falsy值,以确定是否需要重复与否。这最终有没有必要建立2纳克重复块唯一的优势(但事实并非如此糟糕,虽然)。因此,在控制器上的范围,增加一个功能,
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>
Plnkr
Plnkr
相关推荐
最新文章