Both do the same thing but there is one key difference that you noted.
The difference is that the first example defines an array of values when calling app.controller
. Why pass the $scope
as a string value?
Minification
What if you're creating an application that needs to be as efficient as possible so your users don't have to wait any extra milliseconds for it to download. You'll want to minify it.
Minification is a process by which the Javascript code is made as small as possible. It's possible for 500k of Javascript to be minified down to maybe 50k or 100k. This is done by removing extraneous information, comments, spaces, etc.
But in this specific case, minification will usually also change the names of parameters to something smaller.
For example, minification might change this:
Test("This is a test.");
function Test(myLongParameterNameHere) {
console.log(myLongParameterNameHere.length)
}
to this:
a("This is a test");
function a(b) {
console.log(b.length);
}
See how much smaller that is?
However, Angular is analyzing the exact names of the parameters. When it sees the parameter named "$scope", it knows how to add the proper $scope information to that parameter. When a minifier changes that to something else, Angular is confused.
So you can give Angular a hint by specifying an array of strings in the same order as the parameter list, like this:
app.controller('MainController',['$scope', '$timeout', '$rootScope', function($scope, $timeout, $rootScope) {
$scope.title ='to your own string';
$timeout(function() { console.log("Timout fired") }, 500);
$rootScope.test = "Hello World";
}]);
After minification, this controller code might look something like this:
app.controller('MainController',['$scope', '$timeout', '$rootScope', function(a, b, c) {
a.title ='to your own string';
b(function() { console.log("Timout fired") }, 500);
c.test = "Hello World";
}]);
Minifiers will not change the name of strings.
You've told Angular which parameter belongs to its specific Angular counterpart. Even after minification, Angular has the information it needs to do its dependency injection.
TL;DR
Adding the parameter names as strings in an array is entirely optional but it's necessary if you plan to do any minification on your Javascript.