gpt4 book ai didi

javascript - 每 3 个项目拆分 ng-repeat

转载 作者:数据小太阳 更新时间:2023-10-29 04:20:42 27 4
gpt4 key购买 nike

我使用 AngularJS 遍历一个包含事件对象数组和竞争对象数组的 JSON 对象。

我希望显示每个 event在一个表中,然后每个 competitiontd , 但每行只有三个单元格

我正在使用 ng-repeat 返回每个事件的表格列表,但我无法将比赛拆分为新的 <tr>每三个<td>

除了从 JSON 重建我自己的大型对象外,执行我在 Angular 中描述的内容的最佳方法是什么?


当前 View :

<table ng-repeat="listing in listings">
<tr>
<th colspan="3">{{listing.name}}</th>
</tr>
<tr>
<td ng-repeat="competition in listing.competitions">
{{competition.id}} - {{competition.name}}
</td>
</tr>
</table>

期望的输出:

<table>
<tr>
<th colspan="3">Event Name</th>
</tr>
<tr>
<td>competition id - competition name</td>
<td>competition id - competition name</td>
<td>competition id - competition name</td>
</tr>
<tr>
<td>competition id - competition name</td>
<td>competition id - competition name</td>
<td>competition id - competition name</td>
</tr>
</table>

Controller :

app.controller('EventsCtrl', function ($scope, $http) {
$scope.loading = true;

$http.get('scripts/JSON/events.json').then(function (response) {
var listings = response['data'].events;

$scope.listings = listings;
});
});

events.json

{
"events": [
{
"id": 418,
"name": "et ullamco",
"competitions": [
{
"id": 933,
"name": "qui in deserunt occaecat et",
"startTime": 1381092189
},
{
"id": 853,
"name": "eu enim ex incididunt do",
"startTime": 1380708266
},
{
"id": 5738,
"name": "ad est ut aliquip et",
"startTime": 1381366623
},
{
"id": 7599,
"name": "sit ex voluptate aliqua dolor",
"startTime": 1381284106
},
{
"id": 7481,
"name": "laborum consequat deserunt do aliqua",
"startTime": 1380874273
},
{
"id": 3441,
"name": "amet reprehenderit sint sunt proident",
"startTime": 1380554850
},
{
"id": 1959,
"name": "ullamco minim minim in voluptate",
"startTime": 1380651981
}
]
},

最佳答案

您正在使用表格,但数据的语义表明您有一个列表列表。您应该考虑使用 <ul><li> 输出它而不是网格。

<ul ng-repeat="listing in listings">
<li>
<h2>{{listing.name}}</h2>
<ul ng-repeat="competition in listing.competitions">
<li>
{{competition.id}} - {{competition.name}}
</li>
</ul>
</li>
</ul>

使用上述 HTML,您可以很容易地通过 CSS 实现所需的布局。查看 Twitter Bootstrap 或 Foundation 中的“ block 网格”以获取示例。表格通常应该只用于实际上是表格的数据。

但是……

您的问题仍然值得回答,因为可能有其他原因按照您建议的方式替换模板。您可以为此使用一个函数来一次获取三个东西:

<table ng-repeat="listing in listings">
<tr>
<th colspan="3">{{listing.name}}</th>
</tr>
<tr ng-repeat="group in competitions">
<td ng-repeat="competition in group">
{{competition.id}} - {{competition.name}}
</td>
</tr>
</table>

在您的 Controller 中,您可以创建一个“列表的列表”来绑定(bind)到嵌套的转发器

// Adapted from Fresheyeball's solution

$scope.competitions = []
compSet = []
for(var i; i < $scope.listings.competitions; i++){
var competition = $scope.listings.competitions[i];
if( i % 3 ){
$scope.competitions.push(compSet);
compSet = [];
}
compSet.push(competition);
}

关于javascript - 每 3 个项目拆分 ng-repeat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19347790/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com