All for Joomla All for Webmasters

AngularJS Dependency Injection

AngularJS comes with a built-in dependency injection mechanism. It facilitates you to divide your application into multiple different types of components which can be injected into each other as dependencies.

Dependency Injection is a software design pattern that specifies how components get holds of their dependencies. In this pattern, components are given their dependencies instead of coding them within the component.

Modularizing your application makes it easier to reuse, configure and test the components in your application. Following are the core types of objects and components:

  • value
  • factory
  • service
  • provider
  • constant

These objects and components can be injected into each other using AngularJS Dependency Injection.


Value

In AngularJS, value is a simple object. It can be a number, string or JavaScript object. It is used to pass values in factories, services or controllers during run and config phase.

  1. //define a module
  2. var myModule = angular.module(“myModule”, []);
  3. //create a value object and pass it a data. 
  4. myModule.value(“numberValue”100);
  5. myModule.value(“stringValue”“abc”);
  6. myModule.value(“objectValue”, { val1 : 123, val2 : “abc”} );

Here, values are defined using the value() function on the module. The first parameter specifies the name of the value, and the second parameter is the value itself. Factories, services and controllers can now reference these values by their name.

Injecting a value

To inject a value into AngularJS controller function, add a parameter with the same when the value is defined.

  1. var myModule = angular.module(“myModule”, []);
  2. myModule.value(“numberValue”100);
  3. myModule.controller(“MyController”, function($scope, numberValue) {
  4.  console.log(numberValue);
  5. });

Factory

Factory is a function that is used to return value. When a service or controller needs a value injected from the factory, it creates the value on demand. It normally uses a factory function to calculate and return the value.

Let’s take an example that defines a factory on a module, and a controller which gets the factory created value injected:

  1. var myModule = angular.module(“myModule”, []);
  2. myModule.factory(“myFactory”, function() {
  3.     return “a value”;
  4. });
  5. myModule.controller(“MyController”, function($scope, myFactory) {
  6. console.log(myFactory);
  7. });

Injecting values into factory

To inject a value into AngularJS controller function, add a parameter with the same when the value is defined.

  1. var myModule = angular.module(“myModule”, []);
  2. myModule.value(“numberValue”100);
  3. myModule.controller(“MyController”, function($scope, numberValue) {
  4.  console.log(numberValue);
  5. });

Note: It is not the factory function that is injected, but the value produced by the factory function.


Service

In AngularJS, service is a JavaScript object which contains a set of functions to perform certain tasks. Services are created by using service() function on a module and then injected into controllers.

  1. //define a module
  2. var mainApp = angular.module(“mainApp”, []);
  3. //create a service which defines a method square to return square of a number.
  4. mainApp.service(‘CalcService’, function(MathService){
  5.    this.square = function(a) {
  6.       return MathService.multiply(a,a);
  7.    }
  8. });
  9. //inject the service “CalcService” into the controller
  10. mainApp.controller(‘CalcController’, function($scope, CalcService, defaultInput) {
  11.    $scope.number = defaultInput;
  12.    $scope.result = CalcService.square($scope.number);
  13.     $scope.square = function() {
  14.       $scope.result = CalcService.square($scope.number);
  15.    }
  16. });

Provider

In AngularJS, provider is used internally to create services, factory etc. during config phase (phase during which AngularJS bootstraps itself). It is the most flexible form of factory you can create. Provider is a special factory method with a get() function which is used to return the value/service/factory.

  1. //define a module
  2. var mainApp = angular.module(“mainApp”, []);
  3. //create a service using provider which defines a method square to return square of a number.
  4. mainApp.config(function($provide) {
  5.    $provide.provider(‘MathService’, function() {
  6.       this.$get = function() {
  7.          var factory = {};
  8.          factory.multiply = function(a, b) {
  9.             return a * b;
  10.          }
  11.          return factory;
  12.       };
  13.    });
  14. });

Constants

You cannot inject values into the module.config() function. Instead constants are used to pass values at config phase.

  1. mainApp.constant(“configParam”“constant value”);

Let’s take an example to deploy all above mentioned directives.

  1. <!DOCTYPE html>
  2. <html>
  3.    <head>
  4.       <title>AngularJS Dependency Injection</title>
  5.    </head>
  6.    <body>
  7.       <h2>AngularJS Sample Application</h2>
  8.       <div ng-app = “mainApp” ng-controller = “CalcController”>
  9.          <p>Enter a number: <input type = “number” ng-model = “number” /></p>
  10.          <button ng-click = “square()”>X<sup>2</sup></button>
  11.          <p>Result: {{result}}</p>
  12.       </div>
  13.       <script src = “http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js”></script>
  14.       <script>
  15.          var mainApp = angular.module(“mainApp”, []);
  16.          mainApp.config(function($provide) {
  17.             $provide.provider(‘MathService’, function() {
  18.                this.$get = function() {
  19.                   var factory = {};
  20.                   factory.multiply = function(a, b) {
  21.                      return a * b;
  22.                   }
  23.                   return factory;
  24.                };
  25.             });
  26.          });
  27.          mainApp.value(“defaultInput”, 10);
  28.          mainApp.factory(‘MathService’, function() {
  29.             var factory = {};
  30.             factory.multiply = function(a, b) {
  31.                return a * b;
  32.             }
  33.             return factory;
  34.          });
  35.          mainApp.service(‘CalcService’, function(MathService){
  36.             this.square = function(a) {
  37.                return MathService.multiply(a,a);
  38.             }
  39.          });
  40.          mainApp.controller(‘CalcController’, function($scope, CalcService, defaultInput) {
  41.             $scope.number = defaultInput;
  42.             $scope.result = CalcService.square($scope.number);
  43.             $scope.square = function() {
  44.                $scope.result = CalcService.square($scope.number);
  45.             }
  46.          });
  47.           </script>
  48.       </body>
  49. </html>
PinIt
submit to reddit

Leave a Reply

Top