7

Using an Angular ng-repeat, I'm trying to create a carousel with 3 <div>s in each <li>. I can easily create it with 1 div per slide but can't manage to get 3. With js, I'd normally use a modulus (%) to figure out if the index is divisible by 3, and then open/close the li there.

Is this possible to do with Angular?

This is what I have (1 item per slide):

<ul carousel class="carousel">
  <li class="slide" ng-repeat="item in item.list.items" ng-init="itemIndex = $index">
    <div class="item">{{item}}</div>
  </li>
</ul>

This is what I'm trying to achieve (3 items per slide):

<ul class="carousel">

  <!-- slide 1, with 3 items -->
  <li class="slide">
    <div class="item">Item 1</div>
    <div class="item">Item 2</div>
    <div class="item">Item 3</div>
  </li>

  <!-- slide 2, with 3 items -->
  <li class="slide">
    <div class="item">Item 4</div>
    <div class="item">Item 5</div>
    <div class="item">Item 6</div>
  </li>

  <!-- and so on... -->
</ul>

Edit

This question was marked as duplicate by isherwood. The question very clearly asks about using modulus within ng-if, not controllers. The suggested duplicate is close, but Betty St answers the exact question below, with a code sample and link. Thanks Betty!

shackleton
  • 701
  • 1
  • 12
  • 27
  • Possible duplicate of [Splitting ng-repeat every 3 items](http://stackoverflow.com/questions/19347790/splitting-ng-repeat-every-3-items) – ajmajmajma Nov 05 '15 at 19:50

2 Answers2

14

You can use % or groupBy. I always use modulus as described here: https://stackoverflow.com/a/25838091/595152

Your solution should look like this:

<ul carousel class="carousel">
  <li class="slide" ng-repeat="_ in item.list.items" ng-if="$index % 3 == 0">
    <div class="item" ng-repeat="i in [$index, $index + 1, $index + 2]" ng-init="item = item.list.items[i]">
      <div ng-if="item">{{item}}</div>
    </div>
  </li>
</ul>

You need to add a div with ng-if inside the div.item to make sure the item exists ;)

Community
  • 1
  • 1
Betty St
  • 2,741
  • 21
  • 33
2

Take a look at the groupBy filter to group the items into 3 groups.

https://github.com/a8m/angular-filter#groupby

Danny
  • 614
  • 3
  • 11