27.03.2017 Views

ng-book

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Scopes<br />

Scopes are a core fundamental of any A<strong>ng</strong>ular app. They are used all over the framework, so it’s<br />

important to know them and how they work.<br />

The scopes of the application refer to the application model. Scopes are the execution context for<br />

expressions. The $scope object is where we define the business functinality of the application, the<br />

methods in our controllers, and properties in the views.<br />

Scopes serve as the glue between the controller and the view. Just before our app renders the view<br />

to the user, the view template links to the scope, and the app sets up the DOM to notify A<strong>ng</strong>ular<br />

for property cha<strong>ng</strong>es. This feature makes it easy to account for promises, such as an XHR call, to be<br />

fulfilled. See the promises chapter for more details.<br />

Scopes are the source of truth for the application state. Because of this live bindi<strong>ng</strong>, we can rely<br />

on the $scope to update immediately when the view modifies it, and we can rely on the view to<br />

update when the $scope cha<strong>ng</strong>es.<br />

$scopes in A<strong>ng</strong>ularJS are arra<strong>ng</strong>ed in a hierarchical structure that mimics the DOM and thus are<br />

nestable: We can reference properties on parent $scopes.<br />

If you are familiar with JavaScript, then this hierarchical concept shouldn’t be foreign.<br />

When we create a new execution context in JavaScript, we create a new function that<br />

effectively creates a new “local” context. The A<strong>ng</strong>ular concept of $scopes is similar in<br />

that as we create a new scope for child DOM elements, we are creati<strong>ng</strong> a new execution<br />

context for the DOM to live in.<br />

Scopes provide the ability to watch for model cha<strong>ng</strong>es. They give the developer the ability to<br />

propagate model cha<strong>ng</strong>es throughout the application by usi<strong>ng</strong> the apply mechanism available on<br />

the scope. We define and execute expressions in the context of a scope; it is also from here that we<br />

can propagate events to other controllers and parts of the application.<br />

It is ideal to contain the application logic in a controller and the worki<strong>ng</strong> data on the scope of the<br />

controller.<br />

The $scope View of the World<br />

When A<strong>ng</strong>ular starts to run and generate the view, it will create a bindi<strong>ng</strong> from the root <strong>ng</strong>-app<br />

element to the $rootScope. This $rootScope is the eventual parent of all $scope objects.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!