1

I have a circular directive dependency situation.

DirectiveA.template = '<div switch-on="v"> <DirectiveB when="someVal" /> </div>';
DirectiveB.template = '<div> <DirectiveA /> </div>';

What this will do, if you set up this situation, is hang Chrome and eventually crash the page.

I think the reason is because the way the $compile works it will cause endless recursion.

However, as you can see based on my switch statement, there is a recursion terminator clause. As soon as "someVal" is not equal to $scope.v it should end the recursion.

So my question: is there any way to setup a circular dependency between 2 directives?

3
  • create a demo with a simple use case that shows what you are trying to accomplish Commented Oct 27, 2013 at 0:06
  • Unfortunately I can't because as I mentioned it will crash the browser. Just for kicks I tried it in plnkr and then it crashed on me and I lost my work lol. Do I really need to go into more detail? Is anyone actually confused about what my question is asking? Commented Oct 27, 2013 at 0:18
  • post more code then with a better explanation of what you want it to do. Hard to help with what little info is given. Can always comment out the part that causes crash in demo Commented Oct 27, 2013 at 0:22

1 Answer 1

4

So, this is similar to recursive directives. As you have learned, Angular will spin forever. This is because of the way the $compile and link functions work in Angular. To fix it, you need to conditionally compile the circular reference. Here is an example assuming recursion, but the approach is very similar.

Basically, you need to extract your conditional logic from the template into the link function of your directive. In your case, the conditional that will eventually result in the termination of the circluar reference is in DirectiveA. It would look something like this (untested, because I don't have a full example of your code):

app.directive('DirectiveA', function ($compile) {
  return {
    link: function (scope, element) {
      if(scope.v === "circular_condition") {
        element.append('<DirectiveB when="someVal" />');
        $compile(element)(scope);
      }
    }
  }
});

The actual solution might be more complex if scope.v will ever change. You will have to $watch the v property and add/remove the DirectiveB based on the value of v. But that gets into the realm of more normal Angular stuff, so I won't muddy the response with that.

Sign up to request clarification or add additional context in comments.

1 Comment

This was all I needed to know.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.