BAD_SEED
BAD_SEED

Reputation: 5086

keep ng-init variable in synch with assigned $index

I have two nested ng-repeat in both I intesively use respective $index. So for readability sake I "renamed" the first $index using ng-init (i.e.: ng-init="backupIndex = $index"). At the starting point everithing is fine, and backupIndex is always equal to $index.

The problem is if I remove element from the collection binded to the ng-repeat then backupIndex goes out of synch with $index.

Here is a plunker. How can I maintain $index and backupIndex in synch?

Upvotes: 0

Views: 1696

Answers (2)

Kalhan.Toress
Kalhan.Toress

Reputation: 21901

you can do it if u can omit the ng-init part and,

<ul ng-repeat="value in values">
  <span style="display: none"> {{ backupIndex = $index }}</span>
  <li>backUp: <b>{{backupIndex}}</b> $index: <b>{{$index}}</b> <button ng-click="rem(backupIndex)">Remove</button></li>
</ul>

<span style="display: none"> {{ backupIndex = $index }}</span> this line will assign backupIndex value of $index and it will sync with the $index

here is the DEMO


<ul ng-repeat="value in values" ng-init="backupIndex = $index">

ng-init will execute only first time and it will create a ng-repeat's child scope variable called backupIndex and assign it the value of $index and backupIndex not sync with the $index.

var ngInitDirective = ngDirective({
    priority: 450,
    compile: function() {
        return {
            pre: function(scope, element, attrs) {
                scope.$eval(attrs.ngInit);
            }
        };
    }
});

this is the angular.js directive for ng-init. what it do is get the expression in ng-init and Executes the expression on the current scope and returns the result.

In this case: ng-init expression is backupIndex = $index then in scope.$eval(attrs.ngInit); (attrs.ngInit is having the expression of backupIndex = $index) line backupIndex = $index expression executes on the ng-repeat's scope. that mean at this point there is a variable called backupIndex in ng-repeat's scope, with the value of $index and that's it.

Upvotes: 1

Nagy Nick
Nagy Nick

Reputation: 755

You do not need to rename the first index to backupIndex since every ng-repeat creates a new scope, and to if you are inside the second ng-repeat and you want to reach the firsts index, all you need to do is access that using

$parent.$index

DEMO: http://plnkr.co/edit/w8btAZfbGgNGLoYFCTP2?p=preview

Upvotes: 0

Related Questions