Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

controllers using as normal function or array notation

Tags:

angularjs

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.

like image 772
Ben Avatar asked Jul 08 '15 03:07

Ben


2 Answers

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
like image 200
Bhojendra Rauniyar Avatar answered Oct 22 '22 09:10

Bhojendra Rauniyar


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

like image 33
Wayne Ellery Avatar answered Oct 22 '22 08:10

Wayne Ellery