How to get $rootElement from root Angular object

angularjs

Solution

`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

Problem

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?

Original source

Related problems