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!

 

UNDERSTANDING DEPENDENCY INJECTION:

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.

UNDERSTANDING CODE:

<script>

(function () {

angular
.module(‘myApp’)
.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) {
checkAuthorized(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”>

<li>val</li>

</div>

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 https://www.facebook.com/lovebeingengineer/.

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

 

 

Leave a Reply