Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: watch element visibility

Tags:

angularjs

I have an element inside my body which is invisible. I want to trigger a function when it become visible. What is the best practice for this?

here is a plunker to a sample work. In this piece of code, the window should scroll to the '#hiddenObj' div by clicking on the button. but the first click, just the div become visible and the second time the window scrolls.

like image 261
parand87 Avatar asked Jun 27 '15 05:06

parand87


Video Answer


2 Answers

ng-hide=false effectively adds 'display:none' to the element which means the element would not have any position to scroll to in the DOM.

So just set a $watch on the visible state of the element as below

var scrollElement = "#hiddenObj";
$scope.$watch(function() { return angular.element(scrollElement).is(':visible') }, function() {
    scrollTo(scrollElement);
});

see http://plnkr.co/edit/BGBygAWdwU6zv7anx3qO?p=preview

like image 120
sjm Avatar answered Nov 02 '22 08:11

sjm


Angular adds a "ng-hide" class to an element that's hidden with ng-hide/ng-show.

One way to watch if there's been a change is to add a watcher for the element's class, and check if it contains "ng-hide".

scope.$watch(function() { return element.attr('class'); }, function(newValue) { 
    if (newValue.match(/ng-hide/) !== null) {
        // Element is hidden.
    }       
});
like image 45
Reimund Avatar answered Nov 02 '22 10:11

Reimund