How to get $rootElement from root Angular object

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

My objective is to find the root element in an arbitrary Angular project if all I have is the angular object. This obviously isn’t very kosher, so a hacked solution will do.

My first approach to this was to find("[ng-app]"), but this fails on bootstrapped apps. I’ve been playing around with the various angular modules, and I’ve hit an impasse.

I can do angular.injector(['ng']).get('$rootScope') to get the root scope. Why can’t I just do
angular.injector(['ng']).get('$rootElement') to get the root element?

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

angular.injector creates a new injector function, it does not return the one associated with the bootstrapped app.

Services in Angular are singletons in the sense that they are only created once per injector, which means that the following code:

angular.injector(['ng']).get('$rootScope')

Will create a new injector function and a new $rootScope every time it’s executed.

The following line:

angular.injector(['ng']).get('$rootElement')

Will create a new injector function and try to retrieve the $rootElement, which does not exist for the newly created injector.

You need to retrieve the injector of the current app:

angular.element(DOMElement).injector();

For your specific case you can for example find the first element that is associated with a scope and go from there:

var element = document.querySelector('.ng-scope');
var $rootElement = angular.element(element).injector().get('$rootElement');
console.log($rootElement);

Demo: http://plnkr.co/edit/mQ5ZibnV0Jg8DreXn0w9?p=preview

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