Austin Austin - 2 months ago 29
AngularJS Question

Customize ng-repeat in AngularJS for every nth element

I am trying to customize an

ng-repeat
to add something like a
br
tag to every 4th element. I have tried searching around but cannot seem to find a solid answer. Is there a simple way to add conditions to Angular for something like this? my
ng-repeat
is just adding some
spans
with content in them, but I need to start a new line every 4th element.

i.e. I want the following

item1 item2 item3 item4
item5 item6 item7 item8


but right now it just does this

item1 item2 item3 item4 item5 item6 item7 item8


If there are any good articles relating to
ng-repeat
customization (for newbies) I would be thankful for links as well as everything I have found thus far is too difficult to understand.

HTML

<div class="section">
<div ng-repeat="items in MyList">
<img ng-click="AddPoint($index)" src={{items.image}} />
<span>{{items.currentPoint}}/{{items.endPoint}}</span>
</div>
</div>

PSL PSL
Answer

You could just use $index and apply it with ng-if on <br ng-if="!($index%4)" />

<div class="section">
    <div ng-repeat="items in MyList">
      <img ng-click="AddPoint($index)" src={{items.image}} />
      <span>{{items.currentPoint}}/{{items.endPoint}}</span>
      <br ng-if="!(($index + 1) % 4)" />
    </div>
  </div>

Update

Based on the comment, you just need css for this just clear the float every nth element.

.section > div:nth-of-type(4n+1){
  clear:both;
}

Demo

If you are worried about support for older browsers then just add a class on specific condition:-

 <div ng-repeat="items in offensiveMasteries" ng-class="{wrap:!($index % 4)}">

and a rule for .section > div.wrap

Demo

Comments