MOCKSTACKS
EN
Questions And Answers

More Tutorials









Angular Dependency Injection


There is also an option to dynamically request components. You can do it using the $injector service:

myModule.controller('myController', ['$injector', function($injector) {
 var myService = $injector.get('myService');
}]);


Note: while this method could be used to prevent the circular dependency issue that might break your app, it is not considered best practice to bypass the problem by using it. Circular dependency usually indicates there is a flaw in your application's architecture, and you should address that instead.

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.


Conclusion

In this page (written and validated by ) you learned about AngularJS Dependency Injection . What's Next? If you are interested in completing AngularJS tutorial, your next topic will be learning about: AngularJS Events.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.