I have a directive that returns DDO with templateUrl and link properties. My templateUrl contains ngRepeat directive on the div, which contains checkbox element. In my link function I am trying to select all child checkboxes, but they are not added to the DOM at the time my link function is called. If I wrap my select in a $timeout checkboxes will be selected of course. Angular, according to docs, calls functions in following order:
mainDirective->compile->preLink -> firstChildDirective->compile->preLink -> lastChildDirective->compile->preLink->postLink -> firstChildDirective->postLink -> mainDirective->postLink.
According to Angular docs if you return DDO with a link property it is called as postLink, which means in my opinion that all the child checkboxes supposed to be already in the DOM, but this is not the case.
By looking at the angular code I can see that this is the case when you have a compile function and do not have templateUrl:
if (directive.templateUrl) {
assertNoDuplicate('template', templateDirective, directive, $compileNode);
templateDirective = directive;
nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i),
nodeLinkFn, $compileNode, templateAttrs, jqCollection, directive.replace,
childTranscludeFn);
ii = directives.length;
} else if (directive.compile) {
try {
linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
if (isFunction(linkFn)) {
addLinkFns(null, linkFn);
} else if (linkFn) {
addLinkFns(linkFn.pre, linkFn.post);
}
} catch (e) {
$exceptionHandler(e, startingTag($compileNode));
}
}
Also if there is link property and templateUrl directive.compile is being assigned directive.link.
I clearly can see that addLinkFns(null, linkFn) binds link function to postLink when there is no templateUrl but what happens when you have templateUrl with some child directives. Why child checkboxes are not available at the time link function is being called? Thank you for your help!!!
You forget one thing: directives don't have to be static. They can react to changes in the model. And that's what
ng-repeat
does. Elements are created / removed when the model is evaluated. Items could be added at runtime, for instance, then there would be no chance that the checkboxes are in the DOM when your directive is linked, obviously.