我有一个相当大的对象需要在嵌套的ng-repeat循环中迭代
简化版本如下所示:
{{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}
如何跟踪totalEvents计数器值..如何在模板中获得嵌套循环的总迭代次数?
只需使用ng-repeat的$index属性即可达到很多值…
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/>Inner Events = {{$index}} </div> </li> </ul> </div>
这里工作PLUNKER
UPDATE
经过一段时间和一些评论我意识到我的代码没有正确计算总迭代次数,所以我做了一些修改来修复它.
我以某种方式做出的第一个错误我认为事件数量对于每一组都是等于,第二个如果再次超过2组则会失败.
因此,为了跟踪总迭代次数,我设置了一个在代码中称为totalIterations的数组.在这个数组中,我设置了目前已经迭代的总数事件,
例如,在第一组结束时,它将是第一个事件组的长度,第二个组将是第一个和第二个组,依此类推……为了实现这一点,我在这里使用ng-repeat-end指令是最终的代码
<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>
这是最新的PLUNKER