0

How are scope attributes being inherited when scope is not set in Angular directive definition?

In Angular docs (under 'Directive Definition Object') there are two cases: when scope is true or when scope is an object ({}). What if scope is not set or is false. How are attributes inherited in this case for the scope and for it's children?

Andrey Chaschev
  • 16,160
  • 5
  • 51
  • 68
  • A great explanation for this question I found here: [What are the nuances of scope prototypal / prototypical inheritance in AngularJS?](http://stackoverflow.com/questions/14049480/what-are-the-nuances-of-scope-prototypal-prototypical-inheritance-in-angularjs/14049482#14049482) – Andrey Chaschev Oct 13 '13 at 21:21

2 Answers2

2

When scope is set to false(also default value) in directive definition, behavior of scope differs based on whether you are doing transclusion or not.

If you do not transclude, it pretty much uses parent scope. Just as if you did not used a directive and written the linked template directly in the page.

Fiddle

Transclusion always creates a child scope but it's bound to parent scope in a strange way when the directive scope is false. You can "read" parent scope but as soon as you "write" to a property it's not bound to parent scope's same property anymore but now a property on child scope unless that property is an object.

Transcluded Fiddle

Child scope is the ones in green border.

Try changing the parent scope first. Enter something in the "var" input field, you will see that the child scope's var will also change. But when you change var in child scope it's not changing the parent scope, and changing the var in parent scope does not affect child scope as the bond is broken when you wrote to var from child scope. This does not apply to the objects (try the same on sp.var, you will see that you cannot break the "bond"). According to developers this is the expected and/or intended behavior.

Quad
  • 1,708
  • 1
  • 10
  • 22
  • 1
    Good point about transclusion adding another scope @Quad. There's a nice diagram of what happens if you start using multiple scopes like that here: http://stackoverflow.com/questions/16653004/confused-about-angularjs-transcluded-and-isolate-scopes-bindings – KayakDave Oct 13 '13 at 15:06
  • Thank you, this explain the strange behaviour I had with a 3rd-party directive. – Andrey Chaschev Oct 13 '13 at 19:47
  • Really sweet demos! So the transclusion instead of just referencing the parent scope makes a shallow copy. – Andrey Chaschev Oct 13 '13 at 21:08
1

If the scope is set to false (which is the default) then the directive has the same scope as the parent- no new scope is created. Since they share a scope any changes in the parent will be reflected in the directive and vice-versa.

Since this isn't great from an encapsulation standpoint, many recommend using an isolate scope whenever possible (an isolate scope being when you set the scope to {})

KayakDave
  • 24,636
  • 3
  • 65
  • 68