AngularJS Creating Controllers, Minification safe


Example

There are a couple different ways to protect your controller creation from minification.

The first is called inline array annotation. It looks like the following:

var app = angular.module('app');
app.controller('sampleController', ['$scope', '$http', function(a, b){
    //logic here
}]);

The second parameter of the controller method can accept an array of dependencies. As you can see I've defined $scope and $http which should correspond to the parameters of the controller function in which a will be the $scope, and b would be $http. Take note that the last item in the array should be your controller function.

The second option is using the $inject property. It looks like the following:

var app = angular.module('app');
app.controller('sampleController', sampleController);
sampleController.$inject = ['$scope', '$http'];
function sampleController(a, b) {
    //logic here
}

This does the same thing as inline array annotation but provides a different styling for those that prefer one option over the other.

The order of injected dependencies is important

When injecting dependencies using the array form, be sure that the list of the dependencies match its corresponding list of arguments passed to the controller function.

Note that in the following example, $scope and $http are reversed. This will cause a problem in the code.

// Intentional Bug: injected dependencies are reversed which will cause a problem
app.controller('sampleController', ['$scope', '$http',function($http, $scope) {
    $http.get('sample.json');
}]);