Marcelo J Forclaz
Marcelo J Forclaz

Reputation: 728

Insert a row with two columns every four ng-repeat values

I have the next code in Html and AngularJS:

<div class='row'>
    <div class='col-md-6' ng-repeat='post in news'>
        <div class='post-content'>{{ post.title }}</div>
    </div>
</div>

Now, what I need is to push a row with two columns every four posts.

<div class='row'>
    <div class='col-md-6'>
        <div class='add-content'>Something</div>
    </div>
    <div class='col-md-6'>
        <div class='add-content'>Something</div>
    </div>
</div>

How do I do it in AngularJS?

The DOM result what I'm looking for is:

<div class='row'>
    <div class='col-md-6'>
        <div class='post-content'>POST TITLE</div>
    </div>
    <div class='col-md-6'>
        <div class='post-content'>POST TITLE</div>
    </div>
    <div class='col-md-6'>
        <div class='post-content'>POST TITLE</div>
    </div>
    <div class='col-md-6'>
        <div class='post-content'>POST TITLE</div>
    </div>
</div>
<div class='row'>
    <div class='col-md-6'>
       <div class='add-content'>Something</div>
    </div>
    <div class='col-md-6'>
        <div class='add-content'>Something</div>
    </div>
</div>
<div class='row'>
    <div class='col-md-6'>
        <div class='post-content'>POST TITLE</div>
    </div>
    <div class='col-md-6'>
        <div class='post-content'>POST TITLE</div>
    </div>
...

Upvotes: 1

Views: 554

Answers (1)

Chris Noring
Chris Noring

Reputation: 471

essentially you need to be using the built in $index which keeps track on the index it is currently on. Every fourth item implies it should be divisible by four. You also need an ng-if statement to determine wether a dom snippet should be added on said item. Also this calls for the use of the ng-repeat-start instead of ng-repeat. Its seldom used but for this purpose it should work. Code below :

   <div class='row' ng-repeat-start="post in news" >
      <div class='post-content'>{{ post.title }}</div>
   </div> 
   <div class="row" ng-repeat-end  ng-if="($index +1 ) % 4 === 0" >
      <div class='col-md-6'>
        <div class='post-content'>POST TITLE</div>
      </div>
      <div class='col-md-6'>
        <div class='post-content'>POST TITLE</div>
      </div>
   </div>

Upvotes: 2

Related Questions