为什么ng-mouseover不适用于ng-if

时间:2015-09-01 14:24:50

标签: angularjs angularjs-ng-show angularjs-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-如果

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

小提琴:http://plnkr.co/edit/Wb6bjyJdHj5qoH7fxGFJ?p=info

4 个答案:

答案 0 :(得分:5)

您观察到的行为是由ngIf的工作方式引起的 - from the docs

  

请注意,当使用ng删除元素时,如果其范围被销毁   并且在恢复元素时创建新范围。范围   在ngIf中创建的,使用prototypal从其父作用域继承   遗产。这是一个重要的含义,如果使用ngModel   在ngIf中绑定到父级中定义的javascript原语   范围。在这种情况下,对变量内的任何修改   子范围将覆盖(隐藏)父范围中的值。

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

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

答案 1 :(得分:1)

像其他指令一样,

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

答案 2 :(得分:0)

您使用的是window.something.whatever; ,因此您必须使用ng-if

工作plunkr

NG-如果

$parent

答案 3 :(得分:0)

我认为这是因为$ event超出了绑定的范围。 这是一个例子: http://plnkr.co/edit/Wb6bjyJdHj5qoH7fxGFJ?p=preview