AngularJS Fun With Scopes

This entry is part 3 of 9 in the series: AngularJS Learning Series

This is the third in a series of posts detailing my experience learning AngularJS. This post and its accompanying example discusses the handling of scope. AngularJS scopes go hand and hand with the DOM (Document Object Model). DOM objects within a controller reference rely first on their controller counterparts for their property assignments.

The example below includes three controllers: Limericks, Limerick1 and Limerick2. Limerick1 and Limerick2 use identical property names, but each are given unique values. If you look at index.html you’ll see two DIVs with ng-controller references to their respective controller definitions in app.js. Because they’re separate DOM objects, they can use the same property names locally.

Try changing the “Title” and “Field” values within each of the limericks. Notice that only one limerick changes even though its property names are identical to the other limerick. (Sidenote: the example scrolls down quite a bit. To view it on a full page, open it up in plunker and click the eye icon on the right to view the rendered page)

[iajsfiddle fiddle=”Bkcp7″ height=”700px” width=”100%” show=”result,html,js,css,resources” skin=”default”]

AngularJS controllers aren’t limited to local property definitions, though. They also inherit from parent scopes. Look at the DIV that references the Limericks controller. Notice that it wraps around both Limerick1 and Limerick2. This allows Limerick1/2 to inherit from Limericks.

To illustrate inheritance, {{author}} is defined only in Limericks but it’s used within all three controller objects. Try changing the value in the “Global Author” field to see how it changes in all three scopes.

But wait, there’s more! Inherited properties can be modified locally without affecting the parent value. Like {{authors}}, {{pageTitle}} is also only defined in the Limericks controller. Its value is “Pretty Bad Limericks”. The first instance of it on the page is outside of Limerick1 and Limerick2. The second instance is within Limerick1 and the third is within Limerick2.

Try changing the first instance by modifying the value in the “Parent pageTitle” field. Notice that both pageTitles change. Now try changing the value in the “Inherited pageTitle” field. Only the local value changes. Limericks1 {{pageTitle}} is now uncoupled from its parent value since it has been assigned a local one. If you change the first instance again you’ll notice that the Limerick2 instance is still inheriting but Limerick1 is not.

For more information on AngularJS scopes, see the dev documentation.

Series Navigation<< AngularJS Simple CalculatorAngularJS Data Loading and Assignment >>Create an Easy AngularJS Menu >>