prem89 prem89 - 1 year ago 232
AngularJS Question

Increment $index in ng-repeat

How should the $index in

be incremented by a specific value?
For instance in this fiddle 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">

Answer Source

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.range = function(max, step) {
        step = step || 1;
        var input = [];
        for (var i = 0; i <= max; i += step) {
        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)">

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download