Jannis Jannis - 4 months ago 20
jQuery Question

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

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,
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?

Any help would be much appreciated.


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) {
        $('.main').height( $('.site-header').height() -  $('.site-footer').height() );

Explanations how it works: one, two.

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

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