Why does ng-mouseover not work with ng-if

∥☆過路亽.° 提交于 2019-12-10 14:07:29

问题


I'm trying to use "ng-mouseover" directive on an image that has "ng-if" and it doesn't work but If I use "ng-show" directive it works, can everyone tell me why? Or it's an AngularJS problem?

In the AngularJS documentation, I can't read anything about it: 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


回答1:


The behaviour you're observing is caused by how ngIf works - from the docs

Note that when an element is removed using ng-if its scope is destroyed and a new scope is created when the element is restored. The scope created within ngIf inherits from its parent scope using prototypal inheritance. An important implication of this is if ngModel is used within ngIf to bind to a javascript primitive defined in the parent scope. In this case any modifications made to the variable within the child scope will override (hide) the value in the parent scope.

Which basically means that you need to use $parent if you're using ng-if. Like so:

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



回答2:


ng-if like other directives creates a child scope. Your code requires a $parent to point to your 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




回答3:


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

working plunkr

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}}



回答4:


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

here is an example:

http://plnkr.co/edit/Wb6bjyJdHj5qoH7fxGFJ?p=preview


来源:https://stackoverflow.com/questions/32334168/why-does-ng-mouseover-not-work-with-ng-if

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!