简体   繁体   中英

Why should I use $rootScope if I can use $scope.$root?

Since $scope.$root is a reference to $rootScope and therefore the same thing, why should I bother injecting $rootScope when I need to use it if I already have access to it through $scope.$root ? What are the reasons, whether they are AngularJS best practices or general programming best practices, of using $rootScope over $scope.$root ?

For clarity, this is not a question about when to use $rootScope . It's asking why I should use it.

$rootScope : var which points to the parent of all the scopes and can be injected everywhere. All other scopes are children of the $rootScope. They are created via the $new method of the $rootScope thus every scope inherits from the $rootScope.

$scope.$root : holds a reference to the $rootScope.

There Is a difference between using $scope.$root and using $rootScope:

When $scope Is the root, its $root property is null

$scope.$root is only assigned on isolate scopes So you might have a situation where $scope.$root is null. Better use $rootScope instead...

It makes sense to use $rootScope in your application. Like you mentioned, $scope.$root is simply a reference to $rootScope from your current $scope . If you're going to be referencing the root scope, you should inject and use $rootScope since it is an explicit declaration of the top-level $scope .

However, in general, AngularJS best practices usually lead the developer to stray away from using $rootScope . Although it is convenient to have a global scope that can be injected anywhere in your application, it is typically overused and abused causing too many objects to be on the $rootScope objects which can lead to slower performance in larger AngularJS applications.

Typically when I'm thinking about using $rootScope to globally hold something, I stop and think for a minute as to what a better approach might be. Perhaps a better solution could involve injecting a shared service/factory around instead of relying on the $rootScope .

It's a matter of taste to some degree, since it's a known fact that $rootScope === $scope.$root , even though $rootScope is tiny bit more performant and minifies better.

In modern AngularJS apps $scope isn't used much. $scope isn't always available in controllers with controllerAs syntax, including component controllers. $scope isn't available in services, too.

$rootScope is conventionally used instead of $scope.$root when root scope should be referred, for the sake of consistency.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM