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!
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 ;)
Take a look at the groupBy filter to group the items into 3 groups.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.