Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 views
in Technique[技术] by (71.8m points)

javascript - Angular - Watch for ngShow/ngHide Changes in Ancestors that Affect Child DOM Element's Visibility

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.

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.

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

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...