8

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.

1

2 Answers 2

14

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:

  1. Implicit Annotation - your first example code
  2. $inject Property Annotation - the $inject method
  3. Inline Array Annotation - your second example code
Sign up to request clarification or add additional context in comments.

1 Comment

thank a lot Bhojendra Nepal. Your answer is very easy to understand
3

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

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.