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?
Probably the author won't need my answer anymore. Still, for sake of completeness i feel other users might find it useful. The best and most simple solution is to use
$(window).load()
inside the body of the returned function. (alternatively you can usedocument.ready
. It really depends if you need all the images or not).Using
$timeout
in my humble opinion is a very weak option and may fail in some cases.Here is the complete code i'd use:
It depends on how your $('site-header') is constructed.
You can try to use $timeout with 0 delay. Something like:
Explanations how it works: one, two.
Don't forget to inject
$timeout
in your directive:there is a
ngcontentloaded
event, I think you can use itIf you can't use $timeout due to external resources and cant use a directive due to a specific issue with timing, use broadcast.
Add
$scope.$broadcast("variable_name_here");
after the desired external resource or long running controller/directive has completed.Then add the below after your external resource has loaded.
For example in the promise of a deferred HTTP request.
Here is how I do it:
I had the a similar problem and want to share my solution here.
I have the following HTML:
Problem: In the link-function of directive of the parent div I wanted to jquery'ing the child div#sub. But it just gave me an empty object because ng-include hadn't finished when link function of directive ran. So first I made a dirty workaround with $timeout, which worked but the delay-parameter depended on client speed (nobody likes that).
Works but dirty:
Here's the clean solution:
Maybe it helps somebody.