Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nested ng-repeat $parent.$index and $index

I have a strange bug that, unfortunately, I cannot replicate with jsfiddle. I've commented out my entire code (Except libraries,etc) except for the following snippets. Is there something obvious that I don't understand? Any ideas?

This works and prints: (0,0) (0,1) (1,0) (1,1)

<div ng-repeat="i in list">     <div ng-repeat="j in list2">         <div>             ({{$parent.$index}} {{$index}})         </div>     </div> </div> 

However, this piece of code prints: (0,0) (1,1) (0,0) (1,1)

<div ng-repeat="i in list">     <div ng-repeat="j in list2">         <div ng-if="1">             ({{$parent.$index}} {{$index}})         </div>     </div> </div> 

My controller is:

$scope.list  = [1, 2]; $scope.list2 = [1, 2]; 
like image 890
Jason Avatar asked Aug 02 '14 10:08

Jason


People also ask

How do you pass an index in NG-repeat?

Each ng-repeat creates a child scope with the passed data, and also adds an additional $index variable in that scope. So what you need to do is reach up to the parent scope, and use that $index .

What can I use instead of NG-repeat?

You can consider using transclusion inside a custom directive, to achieve the behavior you are looking for without using ng-repeat.

What is $Index in AngularJS?

Stay on the bleeding edge of your favorite technologies. $index is a way to show which iteration of a loop you're in. If we set up an ng-repeat to repeat over the letters in 'somewords', like so: <div ng-app="app"> <div ng-repeat="item in 'somewords'.split('')"> {{$index + 1}}.

Does ng-repeat create a new scope?

Directives that Create Scopes In most cases, directives and scopes interact but do not create new instances of scope. However, some directives, such as ng-controller and ng-repeat, create new child scopes and attach the child scope to the corresponding DOM element.


1 Answers

DEMO FIDDLE

That's because the directive ng-if creates a new scope for itself, when you refer to $parent, it access the immediate $parent's scope, i.e., the inner repeat expression's scope.

So if you want to achieve something you wanted like in the former, you may use this:

<div ng-repeat="i in list">     <div ng-repeat="j in list2">         <div ng-if="1">             ({{$parent.$parent.$index}} {{$parent.$index}})         </div>     </div> </div> 

if you have more than one inner directives, you can use ng-init for storing $index in a variable for references in child scopes.

<div ng-repeat="i in list" ng-init="outerIndex=$index">     <div ng-repeat="j in list2" ng-init="innerIndex=$index">         <div ng-if="1">             ({{outerIndex}} {{innerIndex}})         </div>     </div> </div> 

I strongly suggest you to go through this article on understanding scopes in angular

like image 175
Raghavendra Avatar answered Oct 07 '22 16:10

Raghavendra