1

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>
...
2
  • Where is your ngRepeat? stackoverflow.com/help/mcve Commented Apr 8, 2017 at 22:52
  • Where does content come from for class='add-content' ? Commented Apr 9, 2017 at 3:56

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

4 Comments

Modulo is a nice approach but it's not working as the user expects.
It should be ($index+1) % 4 === 0. You are lucky, I was up to post exactly the same answer ;)
This doesn't produce expected results
what makes you say that? @charlietfl ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.