Angular - 注意影响子 DOM 元素可见性的祖先中的 ngShow/ngHide 变化 [英] Angular - Watch for ngShow/ngHide Changes in Ancestors that Affect Child DOM Element's Visibility

查看:26
本文介绍了Angular - 注意影响子 DOM 元素可见性的祖先中的 ngShow/ngHide 变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个 DOM 元素(绑定到一个表格).我是基于 ngShow 的选项卡控件的下游子级.我住在第二个标签上.当页面呈现时,我存在,但我还没有真正可见.

I am a DOM element (bound to, say, a table). I am the downstream child of an ngShow-based tabs control. I live on the second tab. When the page is rendered, I exist but I am not really visible yet.

当我通过我的非直接父级可见时,当它的 ngShow 表达式变为真时,我想以某种方式得到通知.

I would like to somehow be notified when I become visible through my not-immediate parent, when its ngShow expression becomes true.

这可能吗?我想避免在我自己以外的任何地方添加代码 - 例如,我不想在某处的 tab-changed 事件中添加代码.我宁愿有一种注册方式,通过 ngShow/ngHide 绑定的最外层容器的变化,我的可见性何时发生变化.可以这样做吗?

Is this possible? I would like to avoid adding code anywhere outside myself - for example, I'd rather not add code in a tab-changed event somewhere. I'd rather have a way to register to find out when, via changes in outermost containers that are bound via ngShow/ngHide, my visibility changes. Can this be done?

推荐答案

由于您在指令中有一个范围可用,您可以使用它来监视可见性的变化:

Since you have a scope available in the directive, you could use this to watch for changes in visibility:

scope.$watch(function() { return element.is(':visible') }, function() {
  // Do whatever should happen when the visibility changes
});

这避免了轮询可见性,这可能会影响性能.当然,这假设范围是由任何导致可见性改变的原因应用的.我已经在自己的指令中尝试过,但与 ngShow/ngHide 无关.

This avoids polling the visibility, which could be a performance hit. Of course, this assumes that the scope is applied by whatever causes the visibility to change. I've tried it in my own directive, but not related to ngShow/ngHide.

信用到期的信用:这最初是在这里提出的(不是我提出的):
https://groups.google.com/d/msg/angular/w7Gxa5M_17M/koYCZnsobawJ

Credit where credit is due: this was originally proposed (not by me) here:
https://groups.google.com/d/msg/angular/w7Gxa5M_17M/koYCZnsobawJ

编辑 2014-02-24
几个月后重新审视这个答案,我注意到这有效,但会大大减慢你的消化周期.最佳实践是不要使用诸如此类的昂贵函数进行脏检查.谨慎使用!

EDIT 2014-02-24
Revisiting this answer a few months laters, I have noticed that this works but will slow down your digest cycle quite a bit. Best practice is to not use expensive functions such as this for dirty checking. Use with caution!

这篇关于Angular - 注意影响子 DOM 元素可见性的祖先中的 ngShow/ngHide 变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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