Is $rootScope the parent of the topmost $scope?

All we need is an easy explanation of the problem, so here it is.

I have a shared function which returns of the scope of the topmost element (document) in my AngularJS application.

function topScope() { 
  return angular.element(document).scope();
}

This always works and I am always guaranteed to have access to any subscopes located within the application (whether it be inside controllers or directives).

Here’s an example of what I would use it for:

topScope().$emit('pageReady');

Now I’ve noticed that $rootScope also works the same way.

$rootScope.$emit('pageReady');

Which also works and achieves the same affect. But since $rootScope is designed to be the “$scope off the shelf” scope (any scope created will inherit it’s methods and properties) then does this still mean that it is in fact the topmost scope of the page? Thus being the parent of the scope object attached to the document node?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

$rootScope is a parent scope of all scopes in a given AngularJS application. Since it is possible to bootstrap multiple AngularJS applications on one page (only manually, this can’t be done using ng-app) it is also possible to have multiple $rootScope instances in one HTML documents.

Each $rootScope is “attached” to either the element where ngApp was declared or the element passed into angular.bootstrap as described here.

In short, the $rootScope is a root of all scopes for one AngularJS application but there is no “super-root” scope that would serve as a parent scope of all other scopes for a given HTML document.

In your case using the $rootScope might be OK if you’ve got only one AngularJS application in the whole HTML document.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply