ngBook - Scopes

Scopes are a core fundamental of any Angular app. They are used all over the framework, so it’simportant to know them and how they work.The scopes of the application refer to the application model. Scopes are the execution context for expressions.

The $scope object is where we define the business functinality of the application, the methods in our controllers, and properties in the views. Scopes serve as the glue between the controller and the view. Just before our app renders the view to the user, the view template links to the scope, and the app sets up the DOM to notify Angularfor property changes. This feature makes it easy to account for promises, such as an XHR call, to be fulfilled. See the promises chapter for more details.

Scopes are the source of truth for the application state. Because of this live binding, we can relyon the $scope to update immediately when the view modifies it, and we can rely on the view to update when the $scope changes. $scopes in AngularJS are arranged in a hierarchical structure that mimics the DOM and thus arenestable: We can reference properties on parent $scopes.

If you are familiar with JavaScript, then this hierarchical concept shouldn’t be foreign. When we create a new execution context in JavaScript, we create a new function that effectively creates a new ‘local’ context. The Angular concept of $scopes is similar in that as we create a new scope for child DOM elements,we are creating a new execution context for the DOM to live in.

Scopes provide the ability to watch for model changes. They give the developer the ability to propagate model changes throughout the application by using the apply mechanism available on the scope. We define and execute expressions in the context of a scope; it is also from here that we can propagate events to other controllers and parts of the application.It is ideal to contain the application logic in a controller and the working data on the scope of the controller.

From: ngBook - scopes

0%