我有一个指令,返回带有templateUrl和链接属性的DDO。我的templateUrl在div上包含ngRepeat指令,其中包含复选框元素。在我的链接函数中,我试图选择所有的子复选框,但是在我的链接函数被调用时它们不会被添加到DOM中。如果我在$ timeout中包装我的选择,当然会选中复选框。根据文档,Angular按以下顺序调用函数:在调用时间链接函数时元素不在DOM中吗?
mainDirective-> compile-> preLink - > firstChildDirective-> compile-> preLink - > lastChildDirective-> compile-> preLink-> postLink - > firstChildDirective-> postLink - > mainDirective-> postLink。
根据Angular docs,如果您返回带有链接属性的DDO,它将被称为postLink,这意味着我认为所有子复选框应该已经在DOM中,但事实并非如此。
通过观察角度代码,我可以看到,这样的话,当你有一个编译功能,不具备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));
}
}
而且链路是否存在财产和templateUrl directive.compile正在分配的指令。链接。
我明显可以看到,当没有templateUrl时,addLinkFns(null,linkFn)将链接函数绑定到postLink,但是当你有templateUrl和一些子指令时会发生什么。为什么在链接函数被调用时,子复选框不可用? 谢谢你的帮助!
'ng-repeats'在不习惯时很时髦。在元素完全处于DOM(摘要周期完成)之前,指令中的'link'似乎会触发。因此,您可以将任何DOM操作代码包装在'$ timeout()'中,不需要延迟,只需将它放在循环堆栈的末尾,或者观察要定义的元素属性 – charlietfl