How can I run a directive after the dom has finished rendering?

ghz 1years ago ⋅ 2879 views

Question

I've got a seemingly simple problem with no apparent (by reading the Angular JS docs) solution.

I have got an Angular JS directive that does some calculations based on other DOM elements' height to define the height of a container in the DOM.

Something similar to this is going on inside the directive:

return function(scope, element, attrs) {
    $('.main').height( $('.site-header').height() -  $('.site-footer').height() );
}

The issue is that when the directive runs, $('site-header') cannot be found, returning an empty array instead of the jQuery wrapped DOM element I need.

Is there a callback that I can use within my directive that only runs after the DOM has been loaded and I can access other DOM elements via the normal jQuery selector style queries?


Answer

It depends on how your $('site-header') is constructed.

You can try to use $timeout with 0 delay. Something like:

return function(scope, element, attrs) {
    $timeout(function(){
        $('.main').height( $('.site-header').height() -  $('.site-footer').height() );
    });        
}

Explanations how it works: [one](http://ejohn.org/blog/how-javascript-timers- work/), [two](https://stackoverflow.com/questions/779379/why-does- settimeoutfn-0-sometimes-help#comment14183689_779785).

Don't forget to inject $timeout in your directive:

.directive('sticky', function($timeout)