我有一个列表Reviews
,我需要将其与html绑定,以使类item
的div最多可以有3个子div,此后它应该创建一个具有class的新div item
,最多也可以有3个div,依此类推。
我尝试了以下代码,但没有用:
<div class="item" ng-repeat="_list in Reviews" ng-if="$index % 3 == 0">
<div class="col-md-4 col-sm-6" ng-repeat="_list in Reviews" ng-if="$index < 3">
<p> {{_list.Comment}}</p>
</div>
</div>
编辑:其创建类为item
并具有3个子div的div,然后创建新的类为item
并具有相同的3个子div的div。
示例评论包含4个元素:A,B,C,D 预期的输出:
<div class="item">
<div class="col-md-4 col-sm-6">
<p> A</p>
<p> B</p>
<p> C</p>
</div>
</div>
<div class="item">
<div class="col-md-4 col-sm-6">
<p> D</p>
</div>
</div>
它给出下面的输出:
<div class="item">
<div class="col-md-4 col-sm-6">
<p> A</p>
<p> B</p>
<p> C</p>
</div>
</div>
<div class="item">
<div class="col-md-4 col-sm-6">
<p> A</p>
<p> B</p>
<p> C</p>
</div>
</div>
答案 0 :(得分:1)
您可以按组对数组进行分块,然后对其进行迭代。
angular.module('myApp', [])
.controller('Controller', ['$scope',
function($scope) {
var reviews = [{
"Comment": "a"
}, {
"Comment": "b"
}, {
"Comment": "c"
}, {
"Comment": "d"
}, {
"Comment": "e"
}, {
"Comment": "f"
}];
function chunkArrayInGroups(arr, size) {
var myArray = [];
for (var i = 0; i < arr.length; i += size) {
myArray.push(arr.slice(i, i + size));
}
return myArray;
}
$scope.reviews = chunkArrayInGroups(reviews, 3);
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="Controller">
<div class="item" ng-repeat="chunks in reviews">
<div class="col-md-4 col-sm-6" >
<p ng-repeat="_list in chunks"> {{_list.Comment}}</p>
</div>
</div>
</div>
</div>
答案 1 :(得分:1)
您只能通过HTML来做到这一点:
angular.module('myApp', []).controller('Controller', ['$scope', function($scope) {
$scope.reviews = [
{ "Comment": "a" },
{ "Comment": "b" },
{ "Comment": "c" },
{ "Comment": "d" },
{ "Comment": "e" },
{ "Comment": "f" },
{ "Comment": "g" }
];
}]);
.item{
background-color: #66bfff;
}
p{
margin:5px;
background-color: #c2def3;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="Controller">
<div class="item" ng-repeat='item in reviews' ng-if='$index <= reviews.length / 3 - (reviews.length / 3 == 0 ? 1 : 0)' ng-init='$parentIndex = $index'>
<div class="col-md-4 col-sm-6">
<p ng-repeat='item in reviews' ng-if='($index >= $parentIndex * 3) && ($index <= $parentIndex * 3 + 2)'>{{item.Comment}}</p>
</div>
</div>
</div>
</div>