Angular ng-repeat add bootstrap row every 3 or 4 cols

hugsbrugs picture hugsbrugs · Nov 30, 2014 · Viewed 101k times · Source

I'm looking for the right pattern to inject a bootstrap row class every each 3 columns. I need this because cols doesn't have a fixed hight (and I don't want to fix one), so it breaks my design !

Here is my code :

<div ng-repeat="product in products">
    <div ng-if="$index % 3 == 0" class="row">
        <div class="col-sm-4" >
            ...
        </div>
    </div>
</div>

But it does only display one product in each row. What I want as final result is :

<div class="row">
    <div class="col-sm4"> ... </div>
    <div class="col-sm4"> ... </div>
    <div class="col-sm4"> ... </div>
</div>
<div class="row">
    <div class="col-sm4"> ... </div>
    <div class="col-sm4"> ... </div>
    <div class="col-sm4"> ... </div>
</div>

Can I achieve this with only ng-repeat pattern (without directive or controller) ? The docs introduce ng-repeat-start and ng-repeat-end but I can't figure out how to use it is this use case ! I feel like this is something we often use in bootstrap templating ! ? Thanks

Answer

Duncan picture Duncan · Sep 2, 2015

The top voted answer, while effective, is not what I would consider to be the angular way, nor is it using bootstrap's own classes that are meant to deal with this situation. As @claies mentioned, the .clearfix class is meant for situations such as these. In my opinion, the cleanest implementation is as follows:

<div class="row">
    <div ng-repeat="product in products">
        <div class="clearfix" ng-if="$index % 3 == 0"></div>
        <div class="col-sm-4">
            <h2>{{product.title}}</h2>
        </div>
    </div>
</div>

This structure avoids messy indexing of the products array, allows for clean dot notation, and makes use of the clearfix class for its intended purpose.