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?
$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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With