本文介绍了AngularJS - 内部指令 - 当我用 templateUrl 属性替换模板属性时,postLink 函数调用的顺序会发生变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个奇怪的情况.如果我有一个包含 2 个指令的外部指令

inner-directive1 - 定义了一个模板.

inner-directive2 - 定义了一个 templateUrl.

正如预期的那样,在外部指令 postLink 函数之前调用了内部指令 1 postLink 函数.

但是,在外部指令 postLink 之后调用了内部指令 2 poslink 函数 - 不像预期的那样.

对 postLink 函数的调用是:inner-directive1、outer-directive、inner-directive2,我期待:inner-directive1、inner-directive2、outer-directiveem>.

外部指令的模板是:

请看 JsFiddle

有人知道原因吗?有没有办法让它按预期工作?

JSFiddle - 请查看控制台日志.谢谢,本

解决方案

这就是为什么,来自 Angular 指令文档(http://docs.angularjs.org/guide/directive):

templateUrl - 与模板相同,但模板是从指定的 URL 加载的.由于模板加载是异步的,编译/链接会暂停,直到模板加载完毕.

因此该特定指令将停止链接,直到您的模板加载完毕.在此期间,您的其他指令会跳入并运行.

如果链接函数的时机很重要,则需要直接包含模板,而不是作为 templateUrl.除非有人能想出一个很酷的方法来解决这个问题.

I have a weird situation.If I have an outer directive that contains 2 directives

inner-directive1 - has a template defined.

inner-directive2 - has a templateUrl defined.

The inner-directive1 postLink function is being called before the outer-directive postLink function - as expected.

But, the inner-directive2 poslink function is being called after the outer-directive postLink - NOT as expected.

The calls to the postLink function are : inner-directive1, outer-directive, inner-directive2 and I was expecting : inner-directive1, inner-directive2, outer-directive.

The template for the outer directive is:

<div ng-transclude><div inner1></div><div inner2></div></div>

please look at the JsFiddle

Does anyone know the reason why?And is there a way I can make it work as it is expected ?

JSFiddle - Please look at the console log.Thanks,Ben

解决方案

Here's why, from the Angular directive docs(http://docs.angularjs.org/guide/directive):

So that particular directive stops linking until your template is loaded. During that time your other directives jump in and run.

If the timing of you link function is critical, you'll need to include the template directly instead of as a templateUrl. Unless someone can come up with a cool way around this.

这篇关于AngularJS - 内部指令 - 当我用 templateUrl 属性替换模板属性时,postLink 函数调用的顺序会发生变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 12:41