What is scope in AngularJS?
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: In example 1, 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 ng-app directive & is contains 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.