Ng-mouseover does not work with ng-if

I am trying to use the "ng-mouseover" directive in an image with "ng-if" and this will not work, but if I use the "ng-show" directive, it works, can everyone tell me why? Or is this an AngularJS problem?

In the AngularJS documentation, I can't read anything about this: https://docs.angularjs.org/api/ng/directive/ngMouseover

ng show

<button ng-show="true" ng-mouseover="countOne = countOne + 1" ng-init="countOne=0"> Increment (when mouse is over) </button> Count: {{countOne}} 

ng- if

 <button ng-if="true" ng-mouseover="countTwo = countTwo + 1" ng-init="countTwo=0"> Increment (when mouse is over) </button> Count: {{countTwo}} 

Fiddle: http://plnkr.co/edit/Wb6bjyJdHj5qoH7fxGFJ?p=info

+5
source share
4 answers

The behavior you observe is caused by how ngIf works - from the docs

Please note that when an item is deleted with ng - if its scope is destroyed and when the item is restored, a new scope is created. The volume created in ngIf inherits its parent region using prototype inheritance. An important consequence of this is the use of ngModel in ngIf to bind to the javascript primitive defined in the parent scope. In this case, any changes made to the variable within the child region override (hide) the value in the parent region.

Which basically means you need to use $parent if you are using ng-if . For instance:

 <button ng-if="true" ng-mouseover="$parent.countTwo = countTwo + 1" ng-init="$parent.countTwo=0"> 
+5
source

ng-if , like other directives, creates a child scope. Your code requires $parent to specify the desired scope.

try something like this:

 <p> <button ng-if="true" ng-mouseover="$parent.countTwo = countTwo + 1" ng-init="$parent.countTwo=0"> Increment (when mouse is over) </button> Count: {{countTwo}} </p> 

plunkr

+1
source

You are using ng-if , so you need to use $parent

plunkr works

ng- if

 <button ng-if="true" ng-mouseover="$parent.countTwo = countTwo + 1" ng-init="$parent.countTwo=0"> Increment (when mouse is over) </button> Count: {{countTwo}} 
0
source

I think this is because $ event is beyond the scope of this binding.

 here is an example: http://plnkr.co/edit/Wb6bjyJdHj5qoH7fxGFJ?p=preview 
0
source

All Articles