Dependency Injection in Controllers in case of Minification

Dependency Injection means providing additional parameters to the Controller function on which our controller code may depend. For example, in the below code, we are passing $http as an additional parameter in our controller function which might be used inside the controller function.

// controller code

The problem arises if we minify our javascript file while deploying. The arguments which we have passed in the constructor function will be shortened i.e. $http may be converted to $x in the minified file due to which AngularJS will not be able to recognise the dependencies. We can overcome this problem by using any of the two methods mentioned below.

In the first method, we can use the $inject property in our controller to set the dependencies; $inject is an array of all the dependencies. Rather than defining the controller method inside the contoller() function, what we can do is define it separately.

function MyFirstConroller($scope, $http){
// contoller code 

// setting the $inject property on the controller method
// the order of arguments should be same as in the controller constructor function

// and lastly we can create our controller

In the second method, rather than using the $inject property we pass an array of all the dependencies to the controller() method. The last value in the array after all the dependencies will be the controller’s constructor function.

angular.module('MyFirstModule',[]).comtroller('MyFirstController',['$scope','$http',function($scope, $http){
// controller constructor function code
// the order of arguments should be same as in the controller constructor function
// Angular module without any dependencies

Related Posts

Leave a Reply