What is the difference between these 2:
angular.module('myapp' ,[])
.controller('MyController', function($scope){...});
and
angular.module('myapp' ,[])
.controller('MyController, ['$scope', function($scope){...})];
This is quite complicated for those who new to AngularJS like me. The syntax is too different from Java and C.
Many thanks.
There's nothing difference between them. Both code works same way. But if you use first code and when you minify the code then it will confuse.
Look for an example:
.controller('MyController', function(a){...});//$scope is changed to a
And your code won't work as angularjs code uses $scope variable as it doesn't take first, second, third, and so on parameters.
So, the second code is safer than first as if when you minify the code, it still takes same variable i.e. $scope.
Look for an example:
.controller('MyController', ['$scope', function(a){...})];//a refers to $scope
So, the above code works fine when you minify the code as $scope is injected in place of a. So, if you pass multiple parameters then ordering matters in this example. Look at the following:
.controller('MyController', ['$scope','$timeout', function(s,t){...})];
s is injected as $scope and t is injected as $timeout. So if you change the order of them like ['$timeout','$scope', function(s,t){...})]
then s is $timeout and t is $scope. So, ordering matters in this example but in your first example code ordering won't matter as name matters like $scope, $timeout.
There's also another way to inject variables if you use your first example code like below:
MyController.$inject = ['$scope'];
For multiple parameters,
MyController.$inject = ['$scope','$timeout'];
So, there are mainly three kinds of annotation:
The second is minification safe.
Since Angular infers the controller's dependencies from the names of arguments to the controller's constructor function, if you were to minify the JavaScript code for PhoneListCtrl controller, all of its function arguments would be minified as well, and the dependency injector would not be able to identify services correctly.
Source
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With