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 solutio
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