1

I am learning AngularJS, and am currently trying master Dependency Injection.

When I define a controller, the documentation tells me that specifying dependencies through annotations, and just listing them in the parameter list for the constructor are equivalent. Hence, I should get the same outcome if I write either:

angular
    .module('myapp.controllers', [])
        .controller('MainNavigationController', ['$scope', '$location', function ($scope, $location) { 
            // ... some code
        }]);

or:

angular
    .module('myapp.controllers', [])
        .controller('MainNavigationController', function ($scope, $location) { 
            // ... some code
        });

Is there any practical reasons I should prefer the former, since it seems to be needlessly verbose?

2 Answers 2

1

This syntax is needed when you want to keep your dependency injected when minifying your code (var name will be replaced, so dependencies will be affected) :

angular
    .module('myapp.controllers', [])
        .controller('MainNavigationController', function (a, b) { 
            // ... some code
        });

a, b dependencies doesn't exists ... so code will crash

angular
    .module('myapp.controllers', [])
        .controller('MainNavigationController', ['$scope', '$location', function (a, b) { 
            // ... some code
        }]);

a, b are being tied to real dependency string.. OK after minification

See : https://docs.angularjs.org/guide/di

Sign up to request clarification or add additional context in comments.

Comments

0

The former is used for JavaScript minification, which changes parameter names and thus would break the name-based DI. String values "survive" the minification and let Angular "know" which parameter should be bound to which dependency.

You can use the latter and use https://github.com/btford/ngmin to generate the strings array in build time.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.