2

I am new to AngularJS. I try to find out whats the difference between these two controller definitions:

app.controller('simpleController', ['$scope', function($scope) {
}]);

app.controller('simpleController', function($scope) {
});

I always use the second example, but sometimes I see people using the first example. Why should I do that? Is the controller in the first example inheriting another $scope variable?

4
  • the first example lets you minify your code. I don't know the technical reason though Commented Jan 26, 2015 at 18:55
  • Possible duplicate - stackoverflow.com/questions/18782324/… Commented Jan 26, 2015 at 18:56
  • @Ronnie - it's because angular infers the identities of the dependencies from the parameters provided to the constructor. If those are minified, the dependency injector can't work out the dependencies. Commented Jan 26, 2015 at 18:57
  • Gulp package gulp-ng-annotate npmjs.com/package/gulp-ng-annotate should be able to convert code structured according to example 2 into example 1 structure (i.e. prepare for minification). I have not used it yet though. Commented Jan 26, 2015 at 20:43

2 Answers 2

2

The first example

app.controller('simpleController', ['$scope', function($scope) {
}]);

lets you minify your code

minifer converts $scope to variable a.but its identity is still preserved in the strings. so use first example if you would like to minify your code later.

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

Comments

1

Those two controller definitions do the exact same thing. In the first definition, you're explicitly telling Angular the name of the dependency through the use of a string. This allows you to minify your code, since minifiers do not change the contents of strings.

In the second definition, Angular infers what dependency to inject by looking at the parameter name, and thus minifying this code will break it.

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.