Coo*_*gan 8 javascript angularjs
使用AngularJS,我迭代一个JSON对象,该对象包含一个事件对象数组,包含一个竞争对象数组.
我希望将每个显示event在一个表中,然后每个表示competition一个td,但每行只有三个单元格
我正在使用ng-repeat来返回每个事件的表格列表,但是我很难将比赛分成<tr>每三个一个新的比赛<td>.
除了从JSON重建我自己的大型对象之外,在Angular中执行我所描述的最好的方法是什么?
目前来看:
<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>
Run Code Online (Sandbox Code Playgroud)
期望的输出:
<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>
Run Code Online (Sandbox Code Playgroud)
控制器:
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;
});
});
Run Code Online (Sandbox Code Playgroud)
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
}
]
},
Run Code Online (Sandbox Code Playgroud)
您正在使用表格,但数据的语义表明您有一个列表的列表。您应该考虑使用<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>
Run Code Online (Sandbox Code Playgroud)
您可以使用上面的 HTML 轻松地通过 CSS 实现您想要的布局。查看 Twitter Bootstrap 或 Foundation 中的“块网格”作为示例。表格通常应仅用于实际为表格的数据。
然而...
您的问题仍然值得回答,因为可能有其他原因按照您建议的方式替换模板。您可以使用一个函数来一次获取三个内容:
<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>
Run Code Online (Sandbox Code Playgroud)
在您的控制器中,您可以创建一个“列表列表”来绑定到嵌套转发器
// 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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3810 次 |
| 最近记录: |