Different ways of injecting dependency in an AngularJS Application, Controller, Service, Factory

While working as a AngularJS developer, You should aware about different ways to inject DI into AngularJS Application, Controller, Service and Factory.

  1. Passing a dependency as Function Arguments — Please note that this will break when we minify the JS for Production application
var myApp = angular.module('myApp', []); 
myApp.controller("myController", function($scope, MyService) {
            $scope.visitorsCount = MyService.getVisitorsCount();
}

     2. Passing a dependency as Array Arguments

  • Using the Named function 
var myApp = angular.module('app', []);
function MyController($scope, MyService) {
    $scope.message = MyService.getWelcomeMessage(); // returns "Welcome to yoUVCode !"
};
myApp.controller('MyController', ['$scope', MyController]);
  • Using the Inline Anonymous function
var myApp = angular.module('app', []);
myApp.controller('MyController', ['$scope', 'MyService', function ($scope,MyService) {
    $scope.message = MyService.getWelcomeMessage(); // returns "Welcome to yoUVCode !"
}]);
  1. Passing a dependency using the $inject service
var myApp = angular.module('app', []); 
function MyController($scope, MyService){
    $scope.message= "Welcome to yoUVCode";
}
MyController.$inject = ['$scope', 'MyService'];
myApp.controller('MyController', MyController);

 

Leave a Reply