3

ng-mouseenter doesn't work inside my ng-repeat, it works only outside it. Can you please explain what's happening here? http://plnkr.co/edit/BklqI09raI18RAaqmca2?p=preview

<p ng-repeat="i in [1,2]" ng-init="n=0">
<span ng-mouseenter="n = n + 1">ng-repeat {{i}}</span>
</p>
<p><span ng-mouseenter="n = n + 1">Outside the repeat</span></p>
<pre>n : {{n}}</pre>
3psilon
  • 135
  • 3
  • 11
  • This has nothing to do with `ng-mouseenter` instead this is a scope issue. When inside ng-repeat you are just updating the childscope of each repeated element, which you wont get it outside, if you want then update a property of an object (on the controller scope) . Check out this http://plnkr.co/edit/kTB6qY?p=preview But what exactly you want to do you need to keep track of mouseenter for each item? or everything in the ng-repeat as a whole? – PSL Sep 14 '14 at 16:29
  • Thank u it works using object i totally forgot about controller inheritance issues... :/ – 3psilon Sep 14 '14 at 17:16

1 Answers1

3

When you use ng-repeat, a scope inside it is created. If you want to print n in the parent scope, modify the parent by using $parent in the ng-repeat: ng-mouseenter="$parent.n = $parent.n + 1"

  • Using $parent is a bad practice IMHO.. Imaging if you want to update the grandparent's value or gp's parent's value you will go `parent.parent.etc` which is bad. – PSL Sep 14 '14 at 16:33
  • 1
    @PSL You're probably right. There are many ways to access parent scopes, this answer has several http://stackoverflow.com/a/21454647/2819527 – Espen Henriksen Sep 14 '14 at 16:38
  • Worth to note that ng-if applied on the same element also create its own scope. Yes, parent.parent[...] is a sign of bad code. I think using $parent is valid in this case. No need to stuff up the controller. One level up is required when you use mouseenter and mouseleave on an element which already has ng-repeat or ng-if. There might be some other directives that require the use of $parent. Took me a while, I thought something was broken. – Christian Bonato Mar 11 '16 at 08:06
  • I think $parent was the right answer to this question, as it succinctly tells one why the code didn't work: your var is in another castle. How & why to refactor code not to use $parent is a separate SO question. – Ron Newcomb Sep 30 '16 at 22:39