Gihan
Gihan

Reputation: 4283

AngularJs ng-repeat change loop increment

I'm newbie to AngularJs. I want to use ng-repeat as for(i=0; i < ele.length; i+=2)

I have a table with 4 columns, where I'm going to use ng-repeat

<table>
<tr ng-repeat="i in elements">
   <th>{{i.T}}</th>
   <td>{{i.V}}</td>
   <th>{{elements[($index+1)].T}}</th> <!-- This should be next element of the elements array -->
   <td>{{elements[($index+1)].V}}</td> <!-- This should be next element of the elements array -->
</tr>
</table>

I need to access 2 elements in a single iteration and iteration increment should be 2

I hope this make sense. Please help me.

Please check this html view Plunker

Upvotes: 1

Views: 9241

Answers (3)

Mathew Berg
Mathew Berg

Reputation: 28750

You can create a filter that creates an even copy of the array:

.filter("myFilter", function(){
    return function(input, test){
        var newArray = [];
        for(var x = 0; x < input.length; x+=2){
             newArray.push(input[x]);   
        }
        return newArray;
    }
});

JsFiddle: http://jsfiddle.net/gwfPh/15/

Upvotes: 4

Arun P Johny
Arun P Johny

Reputation: 388316

One solution I can think of involves a change in the data model

Template

<table ng-app="test-app" ng-controller="TestCtrl">
<tr ng-repeat="i in items">

   <th>{{i.T1}}</th>
   <td>{{i.V1}}</td>
   <th>{{i.T2}}</th>
   <td>{{i.V2}}</td>
</tr>
</table>

Controller

testApp.controller('TestCtrl', ['$scope', function($scope) {
    var elements=[]; //This is the dynamic values loaded from server
    for (var i = 0; i < 5; i++) {
        elements.push({
            T : i,
            V : 'v' + i
        });
    }

    //A converter which convert the data elements to a format we can use
    var items = [];
    var x = Math.ceil(elements.length / 2);
    for (var i = 0; i < x; i++) {
        var index = i * 2;
        var obj = {
            T1 : elements[index].T,
            V1 : elements[index].V
        }
        if (elements[index + 1]) {
            obj.T2 = elements[index + 1].T;
            obj.V2 = elements[index + 1].V
        }
        items.push(obj)
    }

    $scope.items = items;

}]);

Demo: Fiddle

Another slightly different approach can be found here.

Upvotes: 0

Sebastien Windal
Sebastien Windal

Reputation: 1414

So if I understand correctly you want to walk your list and alternate th and td's while iterating. If so you could use a ng-switch:

<table>
  <tr ng-repeat="i in elements" ng-switch on="$index % 2">
    <th ng-switch-when="0">{{i.T}}</th> 
    <td ng-switch-when="1">{{i.V}}</td>    
  </tr>
</table>

See Plunker here

Upvotes: 1

Related Questions