我有一个指令,它返回带有templateUrl和链接属性的DDO。我的templateUrl在div上包含ngRepeat指令,其中包含复选框元素。在我的链接函数中,我试图选择所有子复选框,但在调用链接函数时它们不会添加到DOM中。如果我将select包装在$ timeout中,则会选中复选框。根据文档,Angular按以下顺序调用函数:
mainDirective-> compile-> preLink - > firstChildDirective-> compile-> preLink - > lastChildDirective-> compile-> preLink-> postLink - > firstChildDirective-> postLink - > mainDirective-> postLink
根据Angular文档,如果你返回带有链接属性的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));
}
}
此外,如果存在link属性,则指定templateUrl directive.compile为directive.link。
我清楚地看到addLinkFns(null,linkFn)在没有templateUrl时将链接函数绑定到postLink,但是当你的templateUrl带有一些子指令时会发生什么。为什么在调用链接功能时子复选框不可用? 谢谢你的帮助!!!
答案 0 :(得分:0)
你忘了一件事:指令不一定是静态的。他们可以对模型中的变化做出反应。这就是ng-repeat
的作用。在评估模型时创建/删除元素。例如,可以在运行时添加项目,然后当链接指令时,复选框就不会出现在DOM中。