I have a fairly simple directive from which I'm trying to query a separate (but related) DOM element.
Relevant markup:
<a href="#target-id" data-collapsible="isCollapsed">Open</a>
...
<div id="target-id">...</div>
Controller:
app.controller('MyController', ['$scope', function( $scope ) {
$scope.isCollapsed = true;
}]);
Directive:
app.directive('collapsible', function() {
return {
restrict: 'A',
link: function( scope, el, attrs ) {
var target = attrs.href.slice(1); // "target-id"
console.log(document.getElementById(target)); // this will be null
}
};
});
The issue is that the DOM query (document.getElementById(target)
) is running before <div id="target-id">...</div>
is available. I've so far only been able to work around the race-condition by wrapping my query in a $timeout
with a 100-500ms delay, but this feels wrong.
Surely I'm doing something wrong and/or there must be a better way to go about this?
This SO thread outlines a similar issue, but a zero-delay timeout does not work for me.