Żabojad
Żabojad

Reputation: 3095

AngularJS combining the use of two custom directives with shared scope

I have two different custom directives, both having an isolated scope. Is there a way to use both directives on the same element without getting:

Error: Multiple directives [...] asking for isolated scope on ...

I thought that they would share a common scope by doing so but it appears it won't (as I get this error)...

Thanks Tom

Upvotes: 4

Views: 2526

Answers (3)

wuerg
wuerg

Reputation: 1072

There's a summary of how directive scopes can be combined in the reference to the $compile method.

The main points are that isolate scopes are never shared, and that an element can have at most one scope attached to it. If your directives use a child scope instead, then it will be shared between both directives.

  • no scope + no scope => Two directives which don't require their own scope will use their parent's scope
  • child scope + no scope => Both directives will share one single child scope
  • child scope + child scope => Both directives will share one single child scope
  • isolated scope + no scope => The isolated directive will use it's own created isolated scope. The other directive will use its parent's scope
  • isolated scope + child scope => Won't work! Only one scope can be related to one element. Therefore these directives cannot be applied to the same element.
  • isolated scope + isolated scope => Won't work! Only one scope can be related to one element. Therefore these directives cannot be applied to the same element.

Upvotes: 1

crispy
crispy

Reputation: 5877

Well, I think Angular gives you the choice between working with a parent scope and communicating between directives.

You can achieve the latter one by adding an interface in the "master" directive by adding a controller function which the "slave" directive consumes. The slave explicates the dependency via require: '^masterDirective' and can use its interface in the link function.

See the official explanation with a nice example: https://docs.angularjs.org/guide/directive#creating-directives-that-communicate

Upvotes: 0

Żabojad
Żabojad

Reputation: 3095

OK, I've workarounded that issue by using the same controller for my both directives, allowing them to share the scope different from the parent scope...

I'm still interested in any suggestion on that subject.

Upvotes: 2

Related Questions