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?
ngShow and ngHide are two ng directives in AngularJS used to show and hide the elements respectively.
The ng-hide directive hides the HTML element if the expression evaluates to true. ng-hide is also a predefined CSS class in AngularJS, and sets the element's display to none .
The ng-app Directive in AngularJS is used to define the root element of an AngularJS application. This directive automatically initializes the AngularJS application on page load. It can be used to load various modules in AngularJS applications.
AngularJS directives are extended HTML attributes with the prefix ng- . The ng-app directive initializes an AngularJS application. The ng-init directive initializes application data. The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
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!
The best way I found:
link: function (scope, element, attr) {
attr.$observe('ngShow', function (expr) {
scope.$watch(function () {
return $parse(expr)(scope);
}, function (value) {
console.log(value)
})
});
}
Good Luck!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With