Understanding AngularJS Scope Life Cycle

Scope in AngularJS is an object that refers to the application model. It is an execution context for expressions. Scopes in AngularJS are arranged in hierarchical structure which mimic the DOM structure of the application. Scopes can watch expressions as well as propagate events.

Before we dive into the life cycle of Scope, it is important that we fully understand the life cycle of AngularJS application. I recommend that you go through AngularJS life cycle first.

Scope data goes through a life cycle while the application is loaded in the browser. Understanding this life cycle will help us understand the interaction between scope and other AngularJS components, especially templates.

Scope data goes through the following life cycle phases:

  1. Creation
  2. Watcher registration
  3. Model mutation
  4. Mutation observation
  5. Scope destruction

Creation

Scope is initialized during this phase. Once the application gets bootstrapped, $injection service of AngularJS will create the root scope. As the template linking begins, further child scopes are created. A digest loop is also created in this phase that interacts with the browser event loop. This digest loop is responsible to update DOM elements with the changes made to the model as well as executing any registered watcher functions.

Watcher registration

During this phase, watchers are registered on scopes that were created in the previous phase. These watches propagate model changes automatically to the DOM elements.

Model mutation

This phase kicks in when there is a change to the data in scope. When you make the changes in your angular app code, the scope function $apply() updates the model and calls the $digest() function to update the DOM elements and registered watches. When you do the changes to scope inside your angular code like within controllers or services, angular internally calls the $apply() function for you.

Mutation observation

This phase occurs when the $digest() function is executed by the digest loop at the end of $apply() call. When $digest() function executes, it evaluates all watches for model changes. If a value has been changed, $digest() calls the $watch listener and updates the DOM elements appropriately.

Scope destruction

This phase occurs when child scopes are no longer needed and the scopes are removed from the browser’s memory by using $destroy() function of AngularJS framework.

angularjs-scope-life-cycle

Top