Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is $rootScope the parent of the topmost $scope?

Tags:

angularjs

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?

like image 693
matsko Avatar asked Nov 30 '12 05:11

matsko


1 Answers

$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.

like image 172
pkozlowski.opensource Avatar answered Oct 22 '22 04:10

pkozlowski.opensource