Thursday, July 4, 2013

AngularJS - Scope Kata

Scope is where a good part of Angularjs magic happens,  binding allows data to be updated by events on the DOM and for changes of data to be reflected by data in the DOM. Scope is more than just a handle for a bunch of variables and it can behave unexpectedly until you understand what's going on behind the scenes

"Scope is not the model.. it is just a reference to what's happening [inside the dom]" egghead.io tutorial
  • Root scope sits at the top of the scope inheritance, changes to this model can be reflected across all other application scopes which are children of the root scope.
  • Root scope is accesible without direct reference
  • Controller scopes are children of root scope, and variables not found local will be pulled from parent scopes all the way back to root.
  • If you declare 2 of the same controller on a view, they are siblings and each has it's own scope, so variables are not shared between them

Plain Variables

Plain variables lose inheritance as soon as written in child scopes. They are local to the current scope only after that.

Model Variable 

Model variables are declared as properties of an object "model.variable".  These will maintain inheritance from parent to child scopes,  as unlike plain variables,  each child is pulling the model reference from parent and only changing the property on the shared object.

Of course if Controllers are siblings, the scopes are not shared regardless if you use plain variables or model notation variables.

Basic Scope Behavior with Controllers.  Code available https://github.com/lauramoore/angularkata