Dependency Injection in AngularJs!

If you know angularJs even a bit, you must be knowing that apart from magnificent two-way data binding, the biggest thing angularjs brought to the development world were ability to unit test the code and providing ‘reusability’ of code at its best. And this is best accomplished by dependency injection. Though there numerous ways for dependency injection via factory methods, module methods and through controllers. And even in controllers, you can inject services via $inject or through array. Here we are only going to talk about injecting in controllers through array as this is the most widely used one!



As clearly depicted in the diagram, we have a service created and that service is injected at wherever the controller it is required. So, this service could be the one to fetch user’s data or even the in-built ones like filter. So, that you can call them in your code as when needed.



(function () {

.service(‘printService’, printService);                                                    //injecting service ‘printService’ in the angular module

printService.$inject = [‘$rootScope’, ‘$http’];                                                  //injecting http and rootScope in the printService

$scope.result=function printService($rootScope, $http) {                                                     //defining the printService

this.get = function () {
var promise = $http({
url: ‘/api/Print/GetList’,
method: “GET”,
.success(function (success) {
return success;


return promise;


In the front end- you can call result and print its value in for Loop like:

<div ng-repeat=”val in result”>



Hope, it would have made you clear with the  concept. If you still have an any doubt, leave it in the comment section below. Our team would revert back within 24 hours.

Do Follow our Facebook page

Similar Blogs:

Top 10 AngularJs Interview Questions


AngularJs Vs Angular


Forms in AngularJs


Templates And Expressions in AngularJs


$scopes in AngularJs


Services in AngularJs


Controllers in AngularJs

Understanding Two-Way Data Binding in AngularJs


Journey of Angular



About admin 153 Articles
Engineer Diaries started with the need to bridge the huge gap in what we are taught vs what the industry demands. We are based in Delhi, India but our blog is for everyone, in and outside tech industry❤ Feel free to reach out to us at for any business/personal query.

Be the first to comment

Leave a Reply