Search code examples
angularjsangularjs-injector

AngularJS - Error while manually using injector to inject a service


I encounter an issue when trying to manually use angular.injector to inject a service which is opening a dialog, which in turn, uses inside it's template a directive, which uses a dynamic template.

The errors I have in the console are:

1: Unknown provider: $rootElementProvider <- $rootElement <- $location <- $anchorScroll <- ngIncludeDirective <- $location

2: Controller 'ngInclude', required by directive 'ngInclude', can't be found!

Here is the plunker demonstrating the problem

var customSvc = angular.injector(['ng', 'pluginApp']).get("customSvc");
customSvc.testOpenDialog(100, scope);

I also tried building the url and specifying it as a directive attribute and accessing it from the templateUrl function, but also in this case it fails, because the value I receive is just the name of the variable, not the content.

If I avoid injection of the service via angular.injector, the code works, however due to the nature of the application I can't avoid it, besides, I am interested in understanding what is the behind reason of this error, if anyone is kind enough to shed some light into the matter.


Solution

  • The solution is to inject the service in the following way:

       var customSvc = angular.injector(['ng', 'pluginApp', 
          function($provide) {
            var $rootElement = angular.element(document.querySelector('body'));
            $provide.value('$rootElement', $rootElement);
          }]).get("customSvc");
    

    Here is the working plunker