smokingoyster smokingoyster - 1 year ago 89
AngularJS Question

ng-repeat ng-init variable gets out of sync.

I have an ng-repeat method to list some stuff out. There is a nested ng-repeat so I'm using ng-init to track my outer $index.

<div class="row" ng-repeat="product in products" ng-if="$index % 2 == 0" ng-init="current = $index">

<div class="col col-50" ng-repeat="idx in [0,1]" ng-if="(current + idx) < products.length">
<div class="item-product" ui-sref="^.product({productId: products[current + idx].Id})">

<div ng-if="products[current + idx].image">
<img class="full-image" ng-src="{{ products[current + idx].image }}">

<p class="ellipsis"><b>{{ current + idx }} {{ products[current + idx].Name }}</b><br/>

<span ng-if="products[current + idx].Description" class="ellipsis">{{ products[current + idx].Description }}</span></p>


This works fine most of the time. But there are situations where current gets out of sync. If I set a certain filter I end up with 12 products. When I dump out $index and current side by side per row I get the following.

0 - 0
2 - 6
4 - 12
6 - 18
8 - 24
10 - 30

For some reason my current starts jumping by 6. Has anyone else seen this?

Answer Source

Consider tracking the ng-repeat by index to simplify things:

<div ng-repeat="product in products track by $index"></div>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download