Difference in controller declaration in AngularJS - angularjs

I have seen controller being declared in two ways as below. But what diff does this make?
appmodule.controller('Actrl',['$scope',function($scope) {}]);
appmodule.controller('Actrl',function($scope) {});
But, most of the times, the 1st doesn't work. Why?

Both the syntax are same but the first one is preferred (there is a typo, see below description) if you are minifying your code.
Angular resolves the dependency based on the name so when you write appmodule.controller('Actrl',function($scope) {}); syntax, Angular injects the dependency of $scope by reading the argument name $scope. But when your code is minified for production level use then your code will become like:
appmodule.controller('Actrl', function(a) {});
Now, the Angular will not be able to resolve the dependency with the name a. That is why the first approach is used i.e. appmodule.controller('Actrl',['$scope', function($scope) {}]);. Now when your code is minimized for production, your code will be like this:
appmodule.controller('Actrl',['$scope', function(a) {}]);
Now, Angular can match the index based position that a is $scope.
There is a typo in your code where the list should not be closed before the function declaration.
Read the Dependency Annotation for more information on this under the topic Inline Array Annotation.
Angular invokes certain functions (like service factories and
controllers) via the injector. You need to annotate these functions so
that the injector knows what services to inject into the function.
There are three ways of annotating your code with service name
information:
Using the inline array annotation (preferred)
Using the $inject property annotation
Implicitly from the function parameter names (has caveats)
Edit:
Another more detailed description over the two different style: a-note-on-minification:
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.
We can overcome this problem by annotating the function with the names
of the dependencies, provided as strings, which will not get minified.
There are two ways to provide these injection annotations:

[EDIT]
For your first case, this isn't the right syntax. The right one would be to encapsulate in the same array your dependency injection and your controller like the following:
appmodule.controller('Actrl',['$scope', function($scope) {}]);
The difference between both of your definitions is that in the first case you're explicitly specifying your injection dependencies. This will avoid to rename variables name during minification which would break your code. Hence the name in quotes [i.e. those strings] will be used in the minified versions.
Both approach are doing the same thing but the second one is just a syntactic sugar of the first one.

These are just two ways that AngularJS does Dependancy Injection. But this version,
appmodule.controller('Actrl',['$scope',function($scope) {}]);
in particular has been written to handle code minification. It is recommended use this version whenever possible.
To get the difference clear, you must first understand how AngualarJS does dependancy injection. For more details you can refer to:
Understanding Dependency Injection
The "Magic" behind AngularJS Dependency Injection
AngularJS Dependency Injection - Demystified
But to cut the long story short, AngularJS loops through each items by their names in the parameter list, looks up against a list of known names of objects that can be injected and then injects the objects if there is a match.
Let's have a look at an example:
appmodule.controller('myController',function($scope, $log) {
$log.info($scope);
});
Here, since $scope and $log (the order that you specify them in the parameter list doesn't matter here) are known objects to AngularJS, it injects them into myController. But if you were to do:
appmodule.controller('myController',function(someVar) {
// ...
});
AngularJS doesn't know about the parameter someVar and it throws a dependancy error.
Now let's come back to your example. Let me modify your 2nd version a bit:
appmodule.controller('Actrl',function($scope, $log) {
$log.info($scope);
});
If we use a minifier, let's see how this piece of code gets minified. I am using an online minifier for this purpose . After minification, it becomes:
appmodule.controller("Actrl",function(o,l){l.info(o)});
This is because, minifiers usually shorten the variable names to smallest size to save space. Notice how our $scope got renamed to o and $log to l.
Now, if we run this code, AngularJS doesn't know about o and l and it is going to cry about missing dependencies as we understood earlier.
AngularJS deals with this problem using the 1st version of Dependency Injection in your example. If it was:
appmodule.controller('Actrl',['$scope','$log', function($scope, $log) {
$log.info($scope);
}]);
After minification it becomes:
appmodule.controller('Actrl',['$scope','$log',function(o,l){l.info(o)}]);
Here, even though $scope and $log parameters were renamed to o and l respectively, the minifier didn't touch the strings '$scope' and '$log' and their order in the array.
Now when AngularJS injector sees this version using array, it substitutes each item in the parameter list in the function with the corresponding objects in the array (provided the objects are known to AngularJS).
So in our example, even after minification, AngularJS knows that it needs to substitute o with $scope and l with $log. Thus the code runs without any Dependancy Injection errors.
But one important thing is to note here is that, when we use this version the order of the items specified in the array and the parameter list of the function of really matters. That is, if you were to do:
appmodule.controller('Actrl',['$scope','$log', function($log, $scope) {
$log.info($scope);
}]);
, it is going to blow everything up!

Related

Need Help on dependency injection for controller in angularjs [duplicate]

This question already has answers here:
controllers using as normal function or array notation
(2 answers)
Closed 7 years ago.
HI I've seen 2 ways of dependency injection in angularjs controller
Method1:
mainApp.controller('CalcController', function($scope, CalcService, defaultInput) {});
Method2:
mainApp.controller('CalcController', ['$scope', 'CalcService', 'defaultInput',function($scope, CalcService, defaultInput) {}]);
What is the diffrence between method1 and method2?
The second method makes your injections minification safe. The actual parameter names get shortened but by supplying them double it still can be mapped.
So you should use the second method.
Method 1 does not work when you minify the javascript since "CalcService" will be renamed to something like "_a", thats why in version 2, you persist the name since minifiers don't touch strings. Hence the service name is intact.
Method two allows your code to be minified and still function correctly.
Javascript does not have named function parameters, however angular's dependency system kindof extends this to allow for named parameters (thats just its dependency system, not as whole). Thats how it knows what to inject.
However minifying your code renames function parameters breaking angulars injection system.
What angular will do is use the array to find the actual dependency by name, then insert it into the variable of that position in the function. This means the order in the array has to match the order of function parameters that you wish to use.
Official Angular Docs on Dependency Injection -
https://github.com/angular/angular.js/blob/master/docs/content/guide/di.ngdoc#L103

controllers using as normal 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 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:
Implicit Annotation - your first example code
$inject Property Annotation - the $inject method
Inline Array Annotation - your second example code
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

Is there a clearer name to describe the Array Syntax in AngularJS

I can read in AngularJS doc that when using a syntax where dependencies are specified in strings before being used in function. (e.g. .controller('InvoiceController', ['currencyConverter', function(currencyConverter) { [...]), this is called Array Syntax.
Angular uses this array syntax to define the dependencies so that the DI also works after minifying the code, which will most probably rename the argument name of the controller constructor function to something shorter like a.
I'm searching for a clearer, or at least more specialized term to describe this approach, as I think that it sounds weird and means nothing when discuting with co-workers.
This approach is called 'Inline Array Annotation', it is a type of 'Dependency Annotation'.
You are basically annotating the controller so that the injector knows what services to inject into the function.
There are three ways of annotating your code with service name information:
Using the inline array annotation (this is the preferred approach).
Using the $inject property annotation.
Implicitly from the function parameter names (not recommended).
Taken from here.
Inline Array Annotation
What you have in your example. You specify the dependencies in an
in-line array.
myModule.controller('MyController', ['$scope', 'someService', function($scope, someService ... ]
$inject Property Annotation
Here you can use $inject to inject your dependencies.
var MyController = function($scope, someService) ...
MyController.$inject = ['$scope', 'someService'];
myApp.controller('MyController', MyController);
Implicit Annotation
Here you don't specify the dependencies in an array. This causes
problems if you minify your code.
someModule.controller('MyController', function($scope, someService)
The Angular docs specify three terms for injection annotation:
Inference
$inject Annotation
Inline (this is the array syntax to which your question refers)
Perhaps that's the term you're looking for.
https://docs.angularjs.org/api/auto/service/$injector
This parameter of controller is in an array format, hence the array syntax term. I think what you actually need to communicate is that controller takes as parameter a dependency list in an array format.
Basicly what happens is that using Array Syntax instead of just parameters in the function, you make sure that the dependencies are injected exactly as defined in the array syntax. If you would not use the array syntax, there is a chance that the minification of your code renames the dependencies of your controller to a, b, c and your app would not know what you want to inject with a, b, c. While when you use the Array Syntax, your app knows that a stands for the first entry in your array, b for the second, c for the third etc. In other words, It doesn't matter how the dependencies inside the: function() bit are called, as long as the names in the array match the names of the dependencies you want to inject.

AngularJS - dependency injection

I would like to know if there is a difference between the two next lines and why to use one of those (the two work as expected)
phonecatApp.controller('PhoneListCtrl', function($scope, $http) {...});
phonecatApp.controller('PhoneListCtrl', ['$scope', '$http', function($scope, $http) {...}]);
I took it from the official AngularJS tutorial and I know there is an explanation about this modification but I don't understand it...
http://docs.angularjs.org/tutorial/step_05
Thanks in advance!
If you minify your first line you get:
phonecatApp.controller("PhoneListCtrl",function(e,t){})
The dependency injection won't work then, because Angular has no idea what e and t are. Compare that to minifying the second version:
phonecatApp.controller("PhoneListCtrl",["$scope","$http",function(e,t){}])
The function parameters are still renamed, but $scope and $http are given in the array so the injection can go ahead as expected.
There is no difference in terms of functionality. The first one may get messed up if your code is minified because angular resolves from the argument names. The latter has some kind of protection against minification because you are already passing dependencies in array.
AngularJS invokes certain functions (like service factories and controllers) via the injector. You need to annotate these functions so that the injector knows what services to inject into the function. There are three ways of annotating your code with service name information:
Using the inline array annotation (preferred)
Using the $inject property annotation
Implicitly from the function parameter names (has caveats)
For more information, see AngularJS Developer Guide - Dependency Injection

What underlying concept(s) am I not understanding in regard to this AngularJS code snippet?

I've been reading through the tutorial, dev guide, and practicing on my own, but I'm having trouble piecing everything together in my mind with regard to dependency injection.
Question: Within the first code snippet in the linked page below, why is the name of the "service" located in front of $inject and why is the parameter of the service used here again? Or better yet what concepts am I lacking in understanding? I'd like to be able to piece it all together in my head step by step, but I'm still trying to understand how exactly even the globally defined "services/functions" can be written this way.
http://docs.angularjs.org/guide/dev_guide.services.understanding_services
So in that code snippet is injecting the $location service into MyController. So MyController depends on $location so it declares the dependency and its owns the dependency declaration.
Here is the code commented:
// declaring a Controller function
var MyController = function($location) { ... };
// $location service is required by MyController
MyController.$inject = ['$location'];
// Then register the Controller in the module.
// The module is the container that performs DI on the objects within it.
myModule.controller('MyController', MyController);
Typically though you'd do the following to declare the Controller and it's dependencies in one shot that's cleaner. The dependencies are strings at the front of the array before the final function which is the controller being registered. Here is the simpler definition:
myModule.controller('MyController', ['$scope', '$location', function($scope, $location) {
$scope.someFunction = function() {
// do something with $location service in here
};
}]);
Keep in mind this:
"...even the globally defined "services/functions"
The whole point of DI is to not define things globally because global definitions create coupling that make it hard to reuse major portions of your system (ie you can't break apart the system without instantiating the whole thing). Dependency Injection separates the dependency (ie MyController depends on/uses $location service) from where it finds that reference. Beginner developers, and some dense senior devs quite frankly, typically just define things globally and that's how everything gets a reference to their dependencies. DI allows code to simply declare its dependencies so its dependencies can be given to the code by an external entity instead of the code assuming where to get it from. Often this is called the Hollywood Principle - Don't call us we'll call you.
It looks like you're lacking a strong understanding of Dependency Injection in AngularJS.
Once you define a service, it then needs to be injected inside to the controller that is going to use it. The two code samples on that page show the two different methods of injecting the service into the controller.
I'd suggest you look at the docs: AngularJS: Dependency Injection

Resources