Reputation: 386
I am new bee to angular js and I have been using $scope in my coding. However I understood like scope is to use for global variables to make sure I searched on angularJs docs but then found root scope details which are nt clear to me. Does anyone help me understand main difference between rootscope and scope.? When to use.? And how internally it works.?
Upvotes: 2
Views: 660
Reputation: 1755
Scopes have a hierarchy.
Each Angular application has exactly one root scope, but may have several child scopes.
The application can have multiple scopes, because some directives create new child scopes (refer to directive documentation to see which directives create new scopes). When new scopes are created, they are added as children of their parent scope. This creates a tree structure which parallels the DOM where they're attached.
When you have something like:
{{name}}
It will look in the scope for this property. If no such property is found, then it searches the parent scope and so on until the root scope is reached. In JavaScript this behavior is known as prototypical inheritance, and child scopes prototypically inherit from their parents.
If you look at the below picture, in the inner most scope {{name}} resolves to the property in the ng-repeat. In the GreetCtrl scope, it resolves to a property defined in this controller. If this controller didn't define the property and it was defined in $rootScope, the $rootScope value would be shown.
So, the $rootScope is the root, global or top most parent scope:
Every application has a single root scope. All other scopes are descendant scopes of the root scope. Scopes provide separation between the model and the view, via a mechanism for watching the model for changes.
For information on how scope works, see the docs.
Upvotes: 1
Reputation: 1718
$scope is not for global variable it is used within a specific module and it is available across controller whereas $rootscope is like global variables across modules and moreover we can have several $scope but we can have only one $rootscope inside our application i.e $rootscope is used for globla variables and $scope is used for local variable inside a module.
Upvotes: 0