1

Just to mention that, I am a very much newbie in Angularjs.

While writing a controller I see I can use

controller('MyController', ['$scope', function($scope) {}])

or

controller('MyController', function($scope) {})

What is the difference between the both ?

2
  • both are for same purpose. the later might fail if you obfuscate the code. Commented Jan 22, 2015 at 4:58
  • AngularJS' A Note on Minification Commented Jan 22, 2015 at 5:10

3 Answers 3

5

Both are same.

When the javascript code is minified, all local variables in the function are changed to smaller variables to reduce size. for example.

function (largevariablename){
  largevariablename = 123;

}

will be converted to

function (a){
  a= 123;
}

But in case of angular if $scope is minified to s. Then the dependency injection fails searching for s. So angular injector will inject the the string value it finds in the array and inject it instead of the local varaiable in you define it in below way

controller('MyController', ['$scope', function($scope) {}])

So incase if your code in not going to be minified you can use the simple version

controller('MyController', function($scope) {})

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

Comments

2

This is mainly used for minification. When you minify the js

controller('MyController', function($scope) {})

will be converted to

controller('MyController', function(a) {}) 

and it will give the error for a is undefined. When you provide the dependency as

controller('MyController', ['$scope', function($scope) {}])

it will map a to $scope and it will work fine.

Comments

1

In fact, you should not use callbacks(Anonymous Functions) directly to define controllers.

You should use separate functions and $inject module to manually identify your dependencies.

controller('MyController', MyController);

MyController.$inject = ['$scope'];

function MyController($scope){

};

Why use named functions ?

This produces more readable code, is much easier to debug, and reduces the amount of nested callback code.

Why use $inject ?

This technique mirrors the technique used by ng-annotate, which I recommend for automating the creation of minification safe dependencies. If ng-annotate detects injection has already been made, it will not duplicate it.

Also, this safeguards your dependencies from being vulnerable to minification issues when parameters may be mangled.

This is extracted from well-know John Papa Angularjs Style Guide

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.