Controllers using as standard function or array notation

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 pretty tricky for anyone familiar with AngularJS like me. The syntax is too different from Java and C.

Many thanks.

+7
angularjs
source share
2 answers

There is nothing different between them. Both codes work the same. But if you use the first code and when you reduce the code, it will be confused.

See an example:

 .controller('MyController', function(a){...});//$scope is changed to a 

And your code will not work, as angularjs code uses the $ scope variable since it does not accept the parameters of the first, second, third, etc.

So, the second code is safer than the first, as if you minimized the code, it still takes the same variable, i.e. $ scope.

See an example:

 .controller('MyController', ['$scope', function(a){...})];//a refers to $scope 

Thus, the code above works fine when you reduce the code since $ scope is entered instead. So, if you pass a few parameters, then arrange the questions in this example. Take a look at the following:

.controller('MyController', ['$scope','$timeout', function(s,t){...})]; is entered as $ scope, and t is entered as $ timeout. Therefore, if you change their order as ['$timeout','$scope', function(s,t){...})] , then s will be $ timeout, and t will be $ scope. Thus, the ordering of the questions in this example, but in your first example, the ordering of the code does not matter, since the name matters like $ scope, $ timeout.


There is also another way to inject variables if you use your first sample code, as shown below:

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

For several parameters

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

So basically there are three kinds of annotation :

  • Implicit annotation is your first code example.
  • $ inject Property declaration - $ inject method
  • Inline Array Annotation - Your Second Code Example
+13
source share

Secondly, it is safe.

Since Angular determines the dependencies of the controller on the names of the arguments to the functions of the controller’s constructor, if you minimized the JavaScript code for the PhoneListCtrl controller, all its function arguments will also be minimized, and the dependency of the injector will not be able to correctly identify the services.

A source

+2
source share

All Articles