Reputation: 380
I have an ng-repeater with a nested ng-repeater contained within it. In the nested repeater I am trying to track the parents $index value, this works fine. However, when I introduce an ng-if in the same element that has a reference to $parent.$index, the parents index is set to the child's index. Any ideas on this? The code is running here. An example would be, I click on index 1 of parent 0 and get index 1 parent 1 as indexes.
JavaScript
var myApp = angular.module('myApp', []);
myApp.controller('ctrl', function($scope) {
$scope.arr = [["a","b","c"],["d","f","e"],["f","h","i"]];
$scope.logIndex = function(index, parent) {
console.log("index: " + index + ", parent: " + parent);
};
});
HTML
<ul>
<li ng-repeat="i in arr">
<ul>
<li ng-repeat="j in i">
<span ng-click="logIndex($index, $parent.$index)" ng-if="$index > 0">{{ j }}</span>
</li>
</ul>
</li>
</ul>
Upvotes: 3
Views: 1383
Reputation: 123739
That is because ng-if
creates a child scope on the element, so $parent
is actually its immediate ng-repeat's child scope, not the parent one, and the $index is again the same $index inherited from its immediate parent (i.e second ng-repeat's childscope). You can use ng-init
to alias special properties of ng-repeat and use that property instead of using $parent.
<li ng-repeat="i in arr" ng-init="parentIndex=$index">
<ul>
<li ng-repeat="j in i">
<span ng-click="logIndex($index, parentIndex)" ng-if="$index > 0">{{ j }} </span>
</li>
</ul>
</li>
Upvotes: 4