Scoping AngularJS Directives Part 2

This is part 2 in a series on scoping directives with AngularJS. In this post I am going to cover how the three different scoping techniques affect each other when multiple directives are applied to one element.

To begin lets review the three directive scoping techniques available through AngularJS:

  1. inherit scope from the nearest controller scope [default]
  2. create a new scope that is prototypically inherited from the nearest controller scope [scope: true]
  3. create an isolated scope that only has access to the nearest controller scope via parameters or the $parent property. [scope: {}]

First, lets take a look at the first two together (inherited scope and new scope):

You will notice that independently they behave as described above in the list. However, when both are applied to the same element, regardless of order, they have the same scope which is the scope type 2 (new scope).

Next, lets take a look at the first and last together (inherited and isolated scope):

You will notice that independently they behave once again as described above in the list. However, when both are applied to the same element, regardless of order, they have the same scope which is the scope type 3 (isolated scope). This is the most important combination to understand as you other directives may be expecting either direct or prototypical access to the nearest controller scope, but when paired with an isolated scope directive they no longer have this access. This can lead to many unexpected errors. In my opinion isolated scopes should be used only very judiciously and with exact intention understanding this behavior.

Finally, when you apply scope type 2 and scope type 3 together (new scope and isolated scope) you get an error. It won’t allow that combination.

In the next part of this series  (part 3) we are going to examine how transclusion affects directive scoping.

6 thoughts on “Scoping AngularJS Directives Part 2

  1. Pingback: Scoping AngularJS Directives Part 2 | JavaScrip...

  2. Pingback: Scoping AngularJS Directives Part 2 | Spectacle Labs Blog | test

  3. Pingback: Scoping AngularJS Directives Part 2 | AngularJS...

  4. Elliot

    This scoping directive series, Part 1 and 2, represent the clearest descriptions and best illustrations (with code) of the interactions of scope when directives are combined on an element! Helped me tremendously. Thank you for taking the time to publish this. I sincerely hope there is a Part 3 coming soon :)

  5. Pingback: Scope | Pearltrees

Comments are closed.