Ignacio Correia
Ignacio Correia

Reputation: 3668

Nested ng-repeat in the same array level

How can I add a "div" after every each 3 repetitions?

This is my array:

[
   client : "name",
   client : "name",
   client : "name",
   client : "name",
   client : "name",
   client : "name",
   client : "name",
   client : "name",
   client : "name",

]

The result expected is:

<div>name</div>
<div>name</div>
<div>name</div>
<div class="clear"></div>
<div>name</div>
<div>name</div>
<div>name</div>
<div class="clear"></div>
<div>name</div>
<div>name</div>
<div>name</div>
<div class="clear"></div>

Upvotes: 0

Views: 326

Answers (4)

Rajkamal Subramanian
Rajkamal Subramanian

Reputation: 6944

One solution to this can be to use the $index angular variable inside the loop as in this plunker. http://plnkr.co/edit/ycnPtBLmbtV8hwIFTsGd?p=preview

Moreover, the data you have posted is not a valid array or valid json. i'm assuming that you are having to deal with json. If you meant an array, the same $index method can be used for the array also.

Upvotes: 1

Caio Cunha
Caio Cunha

Reputation: 23394

Create a filter that splits your array in groups of three and nest the groups.

The filter should be something like this:

app.filter('split', function() {
  return function(target) {
    var splitted = [];

    if (!target) {
      return target;
    }

    for(var i = 0; i < target.length; i += 3) {
      splitted.push(target.slice(i, i+3));
    }

    return splitted;
 }
});

In your controller, just initialize:

$scope.original = [1, 2, 3, 4, 5, 6, 7, 8, 9];

Finally, this is how your HTML should be:

<div ng-repeat="group in original | split">
  <div ng-repeat="item in group">{{item}}</div>
  <div class="clear"></div>
</div>

You can parametrize the group length. This can be achieved by adding a second param to the filter and passing ng-repeat="group in original | split:3".

Not that the original array is not modified. Here is a working Plunker.

Upvotes: 1

nick
nick

Reputation: 17

Can you just loop through the array, check if that iteration is divisible by three and insert the extra div?

Upvotes: -1

Flo Schild
Flo Schild

Reputation: 5294

Why not split your initial array ?

[
    [
        client : "name",
        client : "name",
        client : "name"
    ],
    [
        client : "name",
        client : "name",
        client : "name"
    ],
    [
        client : "name",
        client : "name",
        client : "name"
    ]
]

Upvotes: 1

Related Questions