prem89 prem89 - 28 days ago 34
AngularJS Question

Increment $index in ng-repeat

How should the $index in

ng-repeat
be incremented by a specific value?
For instance in this fiddle http://jsfiddle.net/Lvc0u55v/11811/ the value needs to be displayed two at a time. So the next iteration should start with third value instead of second value.

<div ng-controller="MyCtrl">
<div ng-repeat="text in arr">
<span>{{arr[$index]}}</span>
<span>{{arr[$index+1]}}</span>
</div>
</div>

Answer

You can do this with a custom function in your controller that returns numbers from 0 to the length of your array, skipping every other value in between.

Modified jsfiddle

Here, I created a function called $scope.range().

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    $scope.arr=['hi1','hi2','hi3','hi4','hi5','hi6','hi7'];

    $scope.range = function(max, step) {
        step = step || 1;
        var input = [];
        for (var i = 0; i <= max; i += step) {
            input.push(i);
        }
        return input;
    };
}

Use this new function in your ng-repeat by specifying the maximum number of elements to use and the number of elements to skip. So, to show every other element in arr, you would use num in range(arr.length, 2).

The function will create and return an array to the ng-repeat that looks like this:

[0, 2, 4, 6]

Your ng-repeat will be repeated four times (once for each item in this array) which corresponds to four rows. Then the two <span> elements will use the current value and the one after it to provide you with two columns.

<div ng-controller="MyCtrl">
  <div ng-repeat="num in range(arr.length, 2)">
    <span>{{arr[num]}}</span> 
    <span>{{arr[num+1]}}</span> 
  </div>
</div>

I've also modified your <span> elements to use arr[num] and arr[num+1] instead of using $index. This provides the results you're looking for.

You can, of course, modify this to use three columns by just changing the 2 to a 3 in the ng-repeat like this: <div ng-repeat="num in range(arr.length, 3)">

See the updated jsfiddle.