AngularJS Dynamically load AngularJS service in vanilla JavaScript


You can load AngularJS services in vanilla JavaScript using AngularJS injector() method. Every jqLite element retrieved calling angular.element() has a method injector() that can be used to retrieve the injector.

var service;
var serviceName = 'myService';

var ngAppElement = angular.element(document.querySelector('[ng-app],[data-ng-app]') || document);
var injector = ngAppElement.injector();

if(injector && injector.has(serviceNameToInject)) {
    service = injector.get(serviceNameToInject);

In the above example we try to retrieve the jqLite element containing the root of the AngularJS application (ngAppElement). To do that, we use angular.element() method, searching for a DOM element containing ng-app or data-ng-app attribute or, if it does not exists, we fall back to document element. We use ngAppElement to retrieve injector instance (with ngAppElement.injector()). The injector instance is used to check if the service to inject exists (with injector.has()) and then to load the service (with injector.get()) inside service variable.