为什么ng-mouseover无法与ng-if一起使用 [英] Why does ng-mouseover not work with ng-if

查看:180
本文介绍了为什么ng-mouseover无法与ng-if一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

在AngularJS文档中,我看不到任何有关它的信息: https://docs.angularjs.org/api/ng/directive/ngMouseover

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

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

推荐答案

您观察到的行为是由 ngIf 的工作方式引起的-来自文档

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


当使用ng删除元素时,如果其作用域被破坏
,并且在恢复该元素时会创建一个新作用域。 ngIf中创建的范围
使用原型
继承从其父范围继承。一个重要的含义是,如果在ngIf中使用ngModel
绑定到父
范围中定义的javascript原语。在这种情况下,对
子作用域内的变量所做的任何修改都会覆盖(隐藏)父作用域中的值。

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 。像这样:

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

这篇关于为什么ng-mouseover无法与ng-if一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆