angular.js icon indicating copy to clipboard operation
angular.js copied to clipboard

Parent directive goes through compile, pre, and post before child directive with templateUrl

Open ryanzec opened this issue 12 years ago • 26 comments

I think there is a bug with the ordering of compile, pre, and post linking functions in parent directives when a child directive uses templateUrl to get the template.

Here are some simple directived, not using the template or templateUrl properties:

http://plnkr.co/edit/gEk3GjuASxrV1L6Kp6Dq?p=preview

Everything happens in the order I expect.

Next we use the template property for the logCompile2 directive:

http://plnkr.co/edit/EOYgf5z82mesixcb1LXU?p=preview

Again everything works as expected.

Finally we use the templateUrl property for the logCompile2 directive:

http://plnkr.co/edit/A55sw6YRCuhvWUi6zQ4Q?p=preview

This is where things go wrong as the parent directive is running through all the steps before any of the steps of the child directives are linked.

Some else played with this that last plunker and added transclusion with weird results too:

http://plnkr.co/edit/0jjwTk8VGoqjSF9se1KZ?p=preview

The documentation states:

Post-linking function

Executed after the child elements are linked. It is safe to do DOM transformation in the
post-linking function.

Either I am miss understanding the documentation or this is a bug as I would except the child directive to compile and run pre/post linking before the parent's post linking would run (as the non-templateUrl example do).

Is this a bug or am I miss understanding something?

I should mention this is an issue with 1.2.23 and 1.3.0-rc.0

ryanzec avatar Sep 01 '14 16:09 ryanzec

There are at least three other issues where similar issues with the order of compile / link functions this have been reported: https://github.com/angular/angular.js/issues/8631 https://github.com/angular/angular.js/issues/8156 https://github.com/angular/angular.js/pull/7304

@petebacondarwin Since you heavily contributed to the transclusion refactor etc. could you take a look at this? It's probably a bigger issue, and not feasible to tackle it for 1.3 But since I don't know the compiler, when these pop up, I cannot really estimate if these issues are valid, if there's single root cause etc.

Narretz avatar Sep 01 '14 21:09 Narretz

@Narretz - I'll try to take a look tomorrow.

petebacondarwin avatar Sep 01 '14 21:09 petebacondarwin

I would be pretty disappointed if this was not fixed for 1.3 as it seems like a pretty big issue.

I mean I am getting around it by using the template property and using jQuery ajax functionality with async turned off but would like to not have to do that hack.

ryanzec avatar Sep 01 '14 21:09 ryanzec

Looking at this now, I am afraid that this is working as expected. You have to remember that as soon as you use templateUrl then you are moving from the synchronous world into the murky world of asynchronicity.

With templateUrl you are basically saying to the compiler that the child directive will finish compiling at some unknown point in the future. The compiler completes its processing (i.e. running post-link function on the current directive) and exits. Later, when the template arrives (asynchronously) the child directives continue their compilation as expected but in a completely new call stack.

You can see that this is similar what happens with directives like ngInclude where compilation completes but then later when the included partial arrives a new load of compilation occurs. It would not make sense to somehow delay completion of compilation for some future asynchronous event. What would be the state of the application during this period?

I am afraid that this particular issue is not going to change in any 1.3 release. It is just something you must be aware of when using templateUrl in directives.

Since you may not have control over what child directives are being used in your applications, you should therefore not rely on your current directive's post link function running after all the post link functions of all child elements. This is actually a general consideration in Angular apps anyway since child elements can always be modified asynchronously after the parent directive has completed compiling based on changes to data: Just think about a situation with ngRepeat on a child element where the data for the ngRepeat is changing dynamically during the application life; each change to the data would trigger new compilations and new postLink functions to be called.

petebacondarwin avatar Sep 02 '14 09:09 petebacondarwin

@petebacondarwin If this is really working as intended, that kinda sucks as it really decreases the usefulness of using the templateUrl the property in the normal sense (at least to me). I guess I am just going to have to make sure my build process pre-loads all the templates to make sure that I can still use the templateUrl property but that it works in a synchronous way (to prevent this issue from happening).

Looking at the document for the latest 1.3.0 build to see if I missed anything about pointing this out and I found:


templateUrl

Same as template but the template is loaded from the specified URL. Because the template loading is asynchronous the compilation/linking is suspended until the template is loaded.


This seems to contradict what you are saying or at a minimum is a bit confusing because of the synchronous workflow for compile/linking. Since the post linking of a parent directive happen after the post linking of a child directive for no template or inline template directives, I would expect the suspension of the parent's post linking to wait for the child directive to finish based on this piece of documentation.

If that is not want this documentation is try to say, I think it should be called out that parent directives will not wait for child directive templates to load, compile, and link if using templateUrl to load template.

I also think this piece of documentation would also have to account for this:


Post-linking function

Executed after the child elements are linked. It is safe to do DOM transformation in the post-linking function.


This seems completely incorrect if you have a child directive that is using templateUrl because the DOM might not even exist at the time of post linking for the parent directive.

I think the documentation really needs to be updated to make this clear because 3 different people after looking at these plunkers though this was a bug (at a minimum not what they would expect) so I know it is not just me misunderstanding the documentation.

ryanzec avatar Sep 02 '14 11:09 ryanzec

@ryanzec - I am afraid that whether you preload the templates or not, as soon as you use templateUrl you are async.

I agree that this is not entirely intuitive. At the very least, as you suggest, we should be highlighting this behaviour in the documentation.

But back to why this is causing problems for you. Can you describe the use case for which this behaviour is problematic? I suspect that it may be that there is some other way around what you are trying to do.

petebacondarwin avatar Sep 02 '14 13:09 petebacondarwin

One way to solve this problem would be making use of $templateCache if you have converted your templates to JS using some grunt/gulp plugin such as html2js in your build process.

wawyed avatar Sep 02 '14 14:09 wawyed

this works as expected. we don't delay parent compilation because that would result in the whole app "stalling" until all templates are loaded asynchronously even in the case when only one deeply nested directive has templateUrl.

But I agree that the docs should be more specific about this. In most cases the behavior doesn't matter and you can safely switch between template and templateUrl. The problems arise only if you have a parent directive that is trying to get hold of child directives or DOM produced by them, but that's not common because more commonly it's the children that are trying to get hold of the parent via require directive property.

@petebacondarwin can you please take a stab at improving the docs. Or please ask @btford if you are still traveling.

IgorMinar avatar Sep 02 '14 14:09 IgorMinar

@wawyed $templateCache won't work because the directive is still going to be considered async. you'd have to use a plugin that rewrites directives to use template instead of templateUrl

IgorMinar avatar Sep 02 '14 14:09 IgorMinar

@IgorMinar yes sorry, forgot to mention that. Define your template as template instead of templateUrl and return it as a string from templateCache.

wawyed avatar Sep 02 '14 14:09 wawyed

@IgorMinar - yes I will update the docs

petebacondarwin avatar Sep 02 '14 14:09 petebacondarwin

Awesome. Please close this bug then. Thanks!

IgorMinar avatar Sep 02 '14 14:09 IgorMinar

Done

petebacondarwin avatar Sep 02 '14 14:09 petebacondarwin

@petebacondarwin I have a directive that assumes a model has been attached to a form however the model is not attached until the child directive is linked because the child directive's template has the element with ng-model on it. I am trying to figure out a way to work around this issue, if I find one, I'll post an updated comment here.

ryanzec avatar Sep 02 '14 14:09 ryanzec

I just ran into this myself and it created a lot of headache for me. I'd expect template and templateUrl to behave exactly the same - just with an inlined or external template. Are there any plans to change this behavior in the future (event if it would be in v2)? As templateUrl shouldn't/can't be made synchronous because of "stalling" the app, I'd expect template to have work asynchronous as well. Or I'd need a different way to get some kind of ordering of registered child directives in a parent directive.

donaldpipowitch avatar Jan 20 '15 12:01 donaldpipowitch

I hit this problem as well, but I've been using html2js to fill the $templateCache as part of my project build tasks. So luckily I was able to simply do the following to avoid the asynchronous load.

{
  template: function () {
    return $templateCache.get('path/to/template.html');
  }
}

atticoos avatar Mar 13 '15 23:03 atticoos

I am getting a different behaviour. Did anyone else run into this?

DirectiveA // templateUrl
    DirectiveB // templateUrl

After DirectiveB's templateUrl is loaded, the template does not seem to be $compile'd, as the directives and curly braces are all not expanded...

UPDATE 20150410: Seems like this is a bug in 1.3.13. It works in 1.3.15 with template, but not in 1.3.13 with template. Will check with templateUrl and update with findings later.

tjwoon avatar Apr 09 '15 07:04 tjwoon

A way to overcome this problem is use $watch to check if the element inside the child directive is not undefined.

Example:

scope.$watch(function() {
    var input = formGroup.querySelectorAll('input')
    if (!input) return // check if its undefined
    // continue to manipulate children elements...
}

raphaklaus avatar May 20 '15 14:05 raphaklaus

One work-around is to use "$timeout" in the post link of the parent directive. This will be better than using the $watch as it executes only once.

//Parent directive
        link: {
          post: function(scope,elem,attr){
              $timeout(function(){
                 //Do child directive related DOM manipulations here
              })
          }    
        }

saigiridhar21 avatar Jul 10 '16 08:07 saigiridhar21

$timeout doesn't work in all cases. If template of child takes a while to download, it will still get linked after that $timeout executes.

costescuandrei avatar Sep 13 '16 06:09 costescuandrei