Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS and ngRepeat - insert additional element every n repeats

I am trying to create a structure where every 7 repeated divs there is an additional div inserted. This div has to belong to the parent, and not be a child of one of the repeated divs.

It isn't enough just to change class, the entire content will be different and entirely different ngShow logic will be used with the additional div.

So for example:

<div id="parent">
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="special-child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="special-child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="special-child"></div>
</div>

That example uses a specific number of divs, the ngRepeat could be any number. It's also important the last result of the ngRepeat puts in an additional div after it, even if it isn't an exact multiple of 7.

The current ngRepeat logic I'm using is:

<div id="parent">
  <div class="child" ng-repeat="o in data"></div>
  <div class="special-child"></div>
</div>

But this doesn't work properly as the additional div is only inserted once after all the repeated divs.

Update with working example

<div id="parent">
  <div class="child" ng-repeat-start="o in data"></div>
  <div class="special-child" ng-if="( $index + 1 ) % 7 == 0 || $last" ng-repeat-end></div>
</div>

This solution requires AngularJS 1.2+

like image 652
Matt McDonald Avatar asked May 19 '14 16:05

Matt McDonald


1 Answers

You need something close to this:

<div ng-repeat="o in data">
  <div class="child"></div>
  <div ng-if="$index % 7 == 0" class="special-child"></div>
</div>
like image 129
Matheus Lima Avatar answered Oct 21 '22 20:10

Matheus Lima