I have seen controller being declared in two ways as below. But what diff does this make?
appmodule.controller(\'Actrl\',[\'$scope\',function($scope) {}]);>
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: