What is scope in AngularJS ?
In this article, we will see what the scope is in AngularJS and how to use Scope, along with understanding its implementation through the examples.
How to use the Scope?
When we make a controller in AngularJS, we will pass the $scope object as an argument. In AngularJS, it creates and injects a different $scope object into each controller in an application. Thus, the data and methods attached to $scope inside one controller cannot be accessed on another controller. Amidst the nested controller, the child controller will acquire the parent controller’s scope object. Accordingly, the child controller can access properties added to the parent controller but the parent controller cannot access properties annexed to the child controller.
Understanding the Scope: If we see an AngularJS application that consists of:
- The HTML view.
- Model, the data which is available for the current view.
Example 1: In this example, we will see the use of the $scope object & will also see how data is transferred from the controller to the view component which is rendered by using interpolation.
Example 2: From the previous example, we have used only single scope, but for larger applications, which may be a section in the HTML DOM that can access certain scopes.
Root Scope: Root scope is a scope that is created on the HTML element which has the ng-app directive & is contained in all the applications. The availability of root scope is in the whole application.
Example 3: If any variable is declared with the same name in the current scope & root scope then the current scope will be used by the application. In this example, we will see how the variable named “color” is used by the current scope.
Difference between $Scope & $rootScope:
$rootScope is a parent object of all “$scope” angular objects created in a webpage.
It is created with the ng-app directive.
It is created with the ng-controller directive.
It is available globally for all the controllers, i.e, the property assigned with “$rootscope” can be used anywhere.
It is available only to the controller that has created it, i.e. the property assigned with “$scope” can’t be used outside the controller in which it is defined.
In this case, every application has at least a single “$rootscope” & its lifecycle is the same as the app.
In this case, every controller can have its own scope, which is not shared with others.