Ali Adravi
Ali Adravi

Reputation: 22743

Angularjs ng-repeat iterate by 2

I have a for loop in my MVC application like this

for(var i = 0; i < data.length; i +=2){
    <div class='@(i== 0? "item active": "item")'>
       <div>
          @Html.Raw(data[i].Description)
       </div>
       <div>
          @Html.Raw(data[i + 1].Description)
       </div>
    </div>
}

I want to convert the above code in angularjs.

Means every loop render the record from current and next array index, say i = 0 then render first and second record detail.

Actually it is big object, for clarity I reduce the code, I want to write the same code in ng-repeat

See the fiddle

Upvotes: 0

Views: 1173

Answers (2)

Ali Adravi
Ali Adravi

Reputation: 22743

I end up with a dirty trick:

<div ng-repeat="item in data" 
     ng-class="{active: $first}" class="item row" 
     ng-if='$index % 2 == 0'> 
      <div class='col-lg-6'>{{ item.a }}</div>
      <div class='col-lg-6'>{{ data[$index + 1].a }}</div> 
</div>

If $index % 2 == 0 only then render, means 0, 2, 4 .. it work as I want.

See to codepen.

Upvotes: 1

matmo
matmo

Reputation: 1379

You essentially want something like this:

<div ng-repeat="dataEntry in data" ng-class="{active: $first}" class="item">
    <div>{{ dataEntry.Description }}</div>
    <div ng-if="!$last">{{ data[$index + 1].Description }}</div>
</div>
  • Use ng-repeat to loop over your data entries
  • Use ng-class to only apply 'active' class to the first entry (you have access to $first, $last, $even, and $odd, (which are booleans) inside of an ng-repeat scope)
  • dataEntry represents each entry for each iteration of your data. Use {{ }} to access and render it's contents
  • You can use $index + 1 to grab the next entry in the array of entries.

I would assume you know that data in this scenario has to be attached / accessible from your $scope.

Upvotes: 0

Related Questions