GRowing GRowing - 2 months ago 21
AngularJS Question

Angularjs - How to keep count of total iterations across nested ng-repeat in the template

I have a fairly large object that needs to be iterated over in nested ng-repeat loops

A simplified version looks like this:

{{totalEvents = 0}}
<div ng-repeat="(mainIndex, eventgroup) in EventsListings">

<ul>
<li ng-repeat="event in eventgroup.events" ng-click="Current(totalEvents)">

<div class="event-item-container" ng-show="eventDetailsView[totalEvents]">
{{totalEvents = totalEvents + 1}}
</div>

</li>

</ul>

</div>
{{totalEvents = 0}


How can I keep track of totalEvents counter value.. How can I get a total number of iterations across nested loops IN the template?

Answer

you can reach many value just using $index property of ng-repeat...

HTML

  <div ng-repeat="eventgroup in EventsListings" ng-init="outerIndex = $index">
    <ul>
      <li ng-repeat="event in eventgroup.events" ng-click="Current(totalEvents)">

        <div class="event-item-container">
          {{event.name}} can have unique value like 
          <br/>(outerIndex) * (eventgroup.events.length) + innerIndex
          <br/>Total Events = {{outerIndex * eventgroup.events.length + $index}}
          <br/>Innder Events = {{$index}}
        </div>

      </li>
    </ul>
  </div>

here is working PLUNKER

UPDATE

After some times and some comments I realized that my code is not calculating total iterations correctly, so I made some changes to fix it.

First mistake I made somehow I thought event numbers will be equals for every set, second one if there are more than 2 sets again it fails.

So for keeping track of total iterations I set an array which is called totalIterations in code. In this array I set total number events we already iterate so far,

For example at the finish of first set it will be length of first event group and for second it will be first and second group, and so on... For achieving this I used ng-repeat-end directive here is the final code

<div ng-repeat="eventgroup in EventsListings" ng-init="outerIndex = $index">
    <ul>
      <li ng-repeat="event in eventgroup.events">

        <div class="event-item-container">
          {{event.name}} can have unique value like
          <br/>Total Events Count = {{totalIterations[outerIndex- 1] + $index}}
          <br/>Innder Events = {{$index}}
        </div>

        <button class="btn btn-success" ng-click="Current({{totalIterations[outerIndex- 1] + $index}})">Current Event</button>

      </li>
      <span ng-repeat-end ng-init="totalIterations[outerIndex] = totalIterations[outerIndex - 1] + eventgroup.events.length"></span>
    </ul>
  </div>

and here is latest PLUNKER

Comments