Introduction To Scope In AngularJS

Introduction To Scope In #AngularJS by @IamJasbeerSingh cc @CsharpCorner  #JavaScript

  • Each Angular application has exactly one root scope but may have several child scopes.
  • We can even make child scopes and isolate scopes.
  • When child scopes are no longer needed, then scope.$destroy() is called to destroy scope.
  • All applications have a root scope that is created on the HTML element that contains ng-app directive.
  • In nested Controllers, child controllers inherit the scope of the parent controller.

This article is about Angular scope, life cycle of scope, and hierarchy of scope.

@CsharpCorner: Introduction To Scope In #AngularJS by @IamJasbeerSingh cc @CsharpCorner #JavaScript

Scope is a JavaScript object that plays the role of the binding part between the View and the Controller. Scope contains the model data. Model data is accessed via $scope in Controllers. Scope is available for both View and Controller.

We pass $scope object as an argument whenever we make a Controller. $scope is passed as first argument to the constructor of the Controller. We can define functions in $scope also.

$scope provides APIs to propagate any Model changes into the View from outside of the Controllers, Services, or event handlers. We can even make child scopes and isolate scopes. Child scope inherits properties from its parent scope while an isolated scope doesn’t. Scopes can watch expressions and propagate events. Properties that are made in Controller can be referred to in the View.

Let’s understand this with an example.

First of all, we will create a Controller and pass $scope object as an argument to the Controller constructor.

All applications have a root scope that is created on the HTML element that contains ng-app directive. This root scope is available in the entire application. This is denoted as $rootScope. All other scopes are descendants of the root scope.

Angular is unaware of model modifications. The whole execution has to go through the Angular execution context using the method called $apply. Only model modifications that occur or execute inside the $apply method are properly accounted for by Angular. Let’s see an example of ng-show.

Scopes are arranged in hierarchical order where $rootScope is at highest level, then child scopes come into play. Scope acts as linker between applications controller and view. Controllers and directives both have reference to scope but they (controller and view) cannot reference each other. Scopes are attached to DOM as $scope data property and can be retrieved for debugging purpose. Scopes can propagate events in similar fashion to DOM events. 

Introduction To Scope In AngularJS

You might also like More from author

Comments are closed, but trackbacks and pingbacks are open.