Difference between $scope and $rootScope

后端 未结 9 1750
孤城傲影
孤城傲影 2020-11-28 02:33

Can anyone explain the difference between $scope and $rootScope?

I think

$scope:

We can get ng-model properties in particular cont

相关标签:
9条回答
  • 2020-11-28 02:58

    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.

    0 讨论(0)
  • 2020-11-28 03:00

    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.

    0 讨论(0)
  • 2020-11-28 03:06

    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.

    0 讨论(0)
提交回复
热议问题