Reputation: 2639
I am using AngularJS 1.5.3
I have a list of items that I want to display in my view. Every 2 items I want to show a new div underneath the first one.
<div class="col text-center" ng-repeat="event in weekDay.events">
<small>{{ event.times }}</small>
</div>
For example, this is the result I want to see:
I am not sure how I can do this with ng-repeat.
Upvotes: 0
Views: 875
Reputation: 1045
Use this below code. it will work
<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>
Please check this below small working example.
!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>
Upvotes: 0
Reputation: 4448
I agree with other answers that say it is simpler to use css to place 2 items in each row, but if you don't want to do that you can try the following
get number of items in your events divided by number of items you want to display in each row (in this case 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);
}
and modify your ng-repeat to display current and next item in each iteration
<div ng-repeat="item in getNumber() track by $index">
<span>{{data[$index * 2]}}</span>
<span>{{data[$index * 2 + 1]}}</span>
</div>
Upvotes: 0
Reputation: 340
You can use $index to get the index of current item in your ng-repeat loop. Then you can check if the current $index is odd if so then your can display your div. Your code should look like this:
<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>
Upvotes: 0
Reputation: 11717
Why don't you have bootstrap to do it ?
<div class="row">
<div class="col-xs-6 text-center" ng-repeat="event in weekDay.events">
<small>{{ event.times }}</small>
</div>
</div>
Upvotes: 2