How to get $rootElement from root Angular object

前端 未结 1 842
渐次进展
渐次进展 2021-02-06 06:06

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

1条回答
  •  不思量自难忘°
    2021-02-06 07:09

    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

    0 讨论(0)
提交回复
热议问题