AngularJS Dependency Injection

AngularJS Dependency Injection

AngularJS Dependency Injection (DI) is a design pattern that deals on components getting hold on their dependencies. An AngularJS injector subsystem is responsible for  creating components; work out their dependencies, and getting them to others as requested. This relives a component from locating the dependency and makes dependencies acceptable. It helps in making components reusable, maintain and test.

Using Dependency injection

Dependency injection is common throughout Angular. You can also use it when creating parts else when providing run and config blocks for a module.

  • AngularJS parts like directives, services, animation and filters are created by an injectable factory method or constructor functions. All these parts can be injected with “service” and “value” components as dependencies.
  • In AngularJS the controllers are created by a constructor function, it is injected with any of the “services” and “values” components as dependencies however, they can be also allowed with special dependencies.
  • In Dependency injection the run method accepts a function; it can be injected with “value”, “constant” and “service”, components as dependencies. Always remember that you cannot inject “providers” into run blocks.
  • In dependency injection the config method accepts a function; it can be injected with “provider” and “constant” components as dependencies. Always remember that you cannot inject “service” and “value” components into configuration.

AngularJS provides a supreme Dependency injection mechanism. DI provides different components which can be injected into each other as dependencies.

  • service
  • factory
  • value
  • constant
  • provider

Factory Methods

The method you create services, filters and directives is with a factory function. Factory methods are included with modules. Suggested the desired way of defining factories is:

angular.module('myModule', [])
.factory('serviceId', ['depService', function(depService) {
  // ...
}])
.directive('directiveName', ['depService', function(depService) {
  // ...
}])
.filter('filterName', ['depService', function(depService) {
  // ...
}]);

Service Method

The service is a singleton JavaScript object containing a set of functions to perform certain tasks. These services are created using the service () functions and then injected into the controller.

//define a module
var mainApp = angular.module("mainApps", []);
...
mainApp.service('CalcService', function(MathService){
      this.square = function(a) {
      return MathService.multiply(a,b);
   }
});
//inject the service "CalcService" into the controller
mainApp.controller('CalcController', function($scope, CalcService, defaultInput) {
      $scope.number = defaultInput;
      $scope.result = CalcService.square($scope.numbers);
 
      $scope.square = function() {
      $scope.result = CalcService.square($scope.numbers);
   }
});

Controllers

The controllers are “classes” or “constructor functions” that are responsible for getting the application behavior that supports the declarative markup in the template. Suggested the desired method of defining Controllers is using the array notation:

someModule.controller('MyController', ['$scope', 'dep1', 'dep2', function($scope, dep1, dep2, dep3) {
  ...
  ...
  $scope.aMethod = function() {
    ...
    ...
  }
  ...
  ...
}]);

Some additional dependencies are made accessible to Controllers:

  • $scop: The Controller is included with an element in the DOM and so is allowed with access to the scope. Another components dependency injection such as services only has access to the $rootScope service.
  • resolve: In this situation if a controller is instantiated as a component of a rout, so any values that are resolved as a component of the route are made available for injection into the controller.

Provider Method

The provider is used by AngularJS internally to create services and factory the time of config phase. See the below mentioned code how script can be used to define MathService that we have created earlier. This method is a special factory method with a method get () which is used to return the value/service/factory.

//define a module
var mainApp = angular.module("mainApp", []);
...
//define a service using provider which create a method square to return square of a number.
mainApp.config(function($provide) {
   $provide.provider('MathService', function() {
      this.$get = function() {
         var factory = {}; 
         factory.multiply = function(a, b) {
            return a * b;
         }
         return factory;
      };
   });
});