Can anyone explain the difference between $scope and $rootScope?
I think
We can get ng-model properties in particular cont
New styles, like John Papa's AngularJS Styleguide, are suggesting that we shouldn't be using $scope
to save current page's properties at all. Instead we should use the controllerAs with vm
approach where the view binds to the controller object itself. Then use a capture variable for this when using the controllerAs syntax. Choose a consistent variable name such as vm, which stands for ViewModel.
You will still need the $scope
for its watching capabilities though.
In other way we can look at this; $rootScope
is global while $scope
is local. When Controller
is assigned to a page, so a $scope
variable can be use here because it binds to this controller. But when we want to share its value across to other controllers or services, then $rootScope
is being used (**there are alternative ways, we can share values across but in this case we want to use $rootScope
).
Your second question about how you define those two words are correct.
Lastly a bit off track, please use $rootScope
with care. Similar to the way you use global variables, can be a pain to debug and you may accidentally change the global variable somewhere inside a timer or something which makes your reading incorrect.
Both are Java script objects and the difference is illustrated by diagram as below.
NTB:
First angular application try to find the property of any model or function in $scope , if it doesn't
found the property in $scope , then it search in parent scope in upper hierarchy. If the property is
still not found in upper hierarchy then angular tries to resolve in $rootscope.