我正在使用AngularJS 1.5.3
我有一个要在视图中显示的项目列表。 每2件物品我想在第一件物品下面显示一个新的div。
<div class="col text-center" ng-repeat="event in weekDay.events">
<small>{{ event.times }}</small>
</div>
我不确定如何使用ng-repeat执行此操作。
答案 0 :(得分:2)
为什么你没有引导来做呢?
<div class="row">
<div class="col-xs-6 text-center" ng-repeat="event in weekDay.events">
<small>{{ event.times }}</small>
</div>
</div>
答案 1 :(得分:0)
您可以使用 $ index 来获取ng-repeat循环中当前项的索引。然后你可以检查当前的$ index是否奇数,如果是,那么你可以显示你的div。 您的代码应如下所示:
<div class="col text-center" ng-repeat="event in weekDay.events">
<small>{{ event.times }}</small>
<div class="my-new-div" ng-if="$index%2==1">
<span>My div stuffs</span>
</div>
</div>
答案 2 :(得分:0)
我同意其他答案,说使用css在每行中放置2个项目更简单,但如果你不想这样做,你可以尝试以下
获取事件中的项目数除以您希望在每行中显示的项目数(在本例中为2)
$scope.getNumber = function() {
console.log($scope.data.length / 2)
if($scope.data.length % 2 == 0)
return new Array($scope.data.length / 2);
else
return new Array(Math.floor($scope.data.length/2) + 1);
}
并修改ng-repeat以显示每次迭代中的当前和下一项
<div ng-repeat="item in getNumber() track by $index">
<span>{{data[$index * 2]}}</span>
<span>{{data[$index * 2 + 1]}}</span>
</div>
答案 3 :(得分:0)
使用以下代码。它会起作用
<div class="col text-center" ng-repeat="event in weekDay.events">
<div ng-show="$index%2==0">
<small>{{ event.times }}</small>
<small>{{ weekDay.events[$index+1].times }}</small>
</div>
</div>
请在下面的小工作示例中查看。
!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body ng-app="app" ng-controller="ctrl">
<div ng-repeat="event in weekDay.events" style="border:1px solid black">
<div ng-show="$index%2==0">
{{event.times}}
{{weekDay.events[$index+1].times}}
</div>
</div>
<script src="../lib/angular.js"></script>
<script>
var app = angular.module('app', []);
app.controller('ctrl', function ($scope) {
$scope.weekDay = {
"events": [
{ "times": "one", "day": "1" },
{ "times": "two", "day": "2" },
{ "times": "three", "day": "3" },
{ "times": "four", "day": "4" },
{ "times": "five", "day": "5" },
{ "times": "six", "day": "6" },
{ "times": "seven", "day": "7" },
{ "times": "eight", "day": "8" },
]
};
});
</script>