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?

moritz.muecke
  • 167
  • 1
  • 1
  • 5
  • the first example lets you minify your code. I don't know the technical reason though – Ronnie Jan 26 '15 at 18:55
  • Possible duplicate - http://stackoverflow.com/questions/18782324/angularjs-minify-best-practice – net.uk.sweet Jan 26 '15 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. – net.uk.sweet Jan 26 '15 at 18:57
  • Gulp package gulp-ng-annotate https://www.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. – Mick Cullen Jan 26 '15 at 20:43

2 Answers2

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.

Nisham Mahsin
  • 1,399
  • 5
  • 19
  • 43
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.

influxd
  • 526
  • 3
  • 8