下面的代码显示ng-repeat
内的数据。我试图在显示每5个元素后包含一个新行:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
var json = {
"modules":
[
{
"category":"Sport",
"title":"Sport New Title",
"description" : "Sport This is description",
"fullDescription" : "fullDescription Sport This is description",
"hrefLink" : "http://www.google.com",
"hrefTitle" : "Google",
"dateAdded" : "11-11-11"
},
{
"category":"News",
"title":"Scala New Title",
"description" : "Scala This is description",
"fullDescription" : "fullDescription Sport This is description",
"hrefLink" : "http://www.google.com",
"hrefTitle" : "Google",
"dateAdded" : "11-11-11"
},
{
"category":"Scala",
"title":"Scala New Title",
"description" : "Scala This is description",
"fullDescription" : "fullDescription Sport This is description",
"hrefLink" : "http://www.google.com",
"hrefTitle" : "Google",
"dateAdded" : "11-11-11"
}
]
};
$scope.ocw = json;
});
<!doctype html>
<html ng-app="plunker" >
<head>
<meta charset="utf-8">
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css">
<script src="http://code.angularjs.org/1.1.4/angular.js"></script>
<script src="app.js"></script>
</head>
Search: <input ng-model="searchText">
<body ng-controller="MainCtrl">
<table class="table table-bordered" ng-repeat="module in ocw.modules | filter:searchText">
<td>
<h3 class="moduletitle">{{ module.category }} {{$index}}</h3>
<p>{{ module.title }}</p>
<p>{{ module.description }}</p>
<p><a href="{{ module.hrefLink }}"> {{ module.hrefTitle }}</a></p>
</td>
<div ng-if={{$index}}" % 5 === 0">
<tr></tr>
</div>
</div>
</table>
</body>
</html>
但问题是<td>
元素被<tr>
包裹。这似乎是由ng-repeat
生成的。这些td
元素可以显示在一行中,每5个元素分开吗?
答案 0 :(得分:0)
试试这个:http://plnkr.co/edit/D7XyPDM8uJzArqcaWtJf?p=preview
首先,使用块方法将实际的JSON划分为行(如here所示)
function chunk(arr, size) {
var newArr = [];
for (var i=0; i<arr.length; i+=size) {
newArr.push(arr.slice(i, i+size));
}
return newArr;
}
json.modules = chunk(json.modules, 5);
然后在你的HTML中使用两个ng-repeat。行中TR的一行和行中每个元素的TD中的一行:
<table class="table table-bordered">
<tr ng-repeat="(rowIndex, row)in ocw.modules">
<td ng-repeat="module in row | filter:searchText">
<h3 class="moduletitle">{{ module.category }} {{$index+(rowIndex*5)}}</h3>
<p>{{ module.title }}</p>
<p>{{ module.description }}</p>
<p><a href="{{ module.hrefLink }}"> {{ module.hrefTitle }}</a></p>
</td>
</tr>
</table>
m59我已经链接的答案也显示了如果你需要“unchucked”使用它,如何重新加入你的数据。