为什么 ng-mouseover 不能与 ng-if 一起使用

Why does ng-mouseover not work with ng-if

我正在尝试对具有 "ng-if" 的图像使用 "ng-mouseover" 指令,但它不起作用,但如果我使用 "ng-show" 指令,它会起作用,每个人都可以告诉我为什么?还是 AngularJS 问题?

在 AngularJS 文档中,我无法阅读有关它的任何内容:https://docs.angularjs.org/api/ng/directive/ngMouseover

ng-显示

<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

您正在使用 ng-if 所以您必须使用 $parent

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

ng-if 像其他指令一样创建一个子作用域。您的代码需要一个 $parent 来指向您想要的范围。

尝试这样的事情:

<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

您观察到的行为是由 ngIf 的工作方式引起的 - 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.

这基本上意味着如果您使用 ng-if,则需要使用 $parent。像这样:

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

我认为这是因为 $event 超出了该绑定的范围。

here is an example:

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