Scopes in Angularjs

$Scope is a core fundamental component of an Angular app. Scopes of the Angular app refer to the model. Scope provides a bridge 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 Angular for property changes.

$Scopes are the source of truth for the application state. Because of this live binding, we can rely on the $scope to update immediately when the View modifies it, and we can rely on the View to update when the $scope changes.

$Scopes help to propagate model changes. When Angular runs and generates the View, it will create a binding from the root ng-app element to the $rootScope. This $rootScope is the parent of all $scope objects.

$Scope object is a plain old JavaScript object. We can add and change properties of the $scope object. $scope object is the data model in Angular.

The $Scope object is simply a connection between the View and the HTML. It’s the bridge between the View and the Controller. All properties found on the $Scope object are automatically accessible to the View.

For example,
  1. <div ng-app="myApp">  
  2.    <h1>Hello {{ name }}</h1>  
  3. </div>  
The {{ name }} variable is to be a property of the containing $Scope.
  1. angular.module('myApp', [])  
  2. .run(function($rootScope) {  
  3.    $rootScope.name = "World";  
  4. });  
  5. $Scope Lifecycle  
Creation

When we create a Controller or directive, Angular creates a new scope with the $injector and passes this new scope for the controller or directive at runtime.

Linking

When the $Scope is linked to the View, all directives that create $Sscopes will register their watches on the parent scope. These watches watch for and propagate the model changes from the View to the directive.

Updating

During the $digest cycle, which executes on the $rootScope, all of the children scopes will perform dirty digest checking. All of the watching expressions are checked for any changes, and the scope calls the listener callback when they are changed.

Destruction

When a $scope is no longer needed, the child scope creator will need to call scope.$destroy() to clean up the child scope.