Why element is not available in directive link function

You've probably heard this as many times as I have. "Do all your DOM manipulation in directives." But nobody ever says what can happen if you actually do DOM manipulation outside of a directive in Angular.

I have a problem that I was able to reproduce in this Plunk

I made a very simple directive that just prints the item to the console.

app.directive('dirre', function(){
  return {
    link: function(scope, element, attrs){
      console.log({message:"dirrens linkFn", element: element, count: element.length})
    }
  }
});

      

I have two identical jQuery UI accordions, the only difference is how they are called. One of them is called in the controller and the other in the directive. Calling an accordion from a controller is, of course, bad.

As you can see, if you run the application, there is a situation where one of the dirre directives has no element, but there are no errors.

The same thing happens in the large application I am currently working with. The problem is that someone on our team decided to name the jQuery UI accordion in the controller and not in the directive. I haven't been able to step through the code to see what is actually going on, but I strongly suspect that the DOM has been modified and Angular is compiling and something is wrong. Is this a plausible explanation?

Is this an example of what can go wrong if you are doing DOM manipulation outside of a directive?

+3


source to share


1 answer


The controller and directive links function are named asynchronously. You can usually see the directives build before the main controller finishes. When the controller exits, the directives update their watched variable (ngModel, $ watch (something) ...). This is mostly done with promises.



However, the link / compile function is not called. You have to compile, see, apply the new DOM. Which basically means writing similar code in angularjs.

0


source







All Articles