-2

in Angularjs's developer guide a controller created in below schema:

.controller('MyController', ['$scope', function($scope) {
  $scope.username = 'World';
}]);

but i see in some other places they use another way to create their controllers like below:

.controller('MyController', function($scope) {
  $scope.username = 'World';
});

What is Differences when we use brackets in controller definition or not?

3
  • Imagine what will happen with the 2nd example when you minify. Commented Dec 18, 2014 at 16:42
  • 1
    See docs.angularjs.org/tutorial/step_05#a-note-on-minification Commented Dec 18, 2014 at 16:43
  • I think, the first one is a little bit faster as all the dependencies in the list as far as I know the other method parses function.toString() (no sure if here a method to get parameters directly) Commented Dec 18, 2014 at 16:48

1 Answer 1

2

It allows for code minification. With Angular's dependency injection, the names of the variables (as the function parameters) being injected matter, and a code minifier could change them. If you provide the string versions of the variable names (in order), Angular will be able to inject the correct dependency even if the minifier changed the variable name.

If you had the original code:

.controller('MyController', function ($http) {

Then Angular's DI knows to inject the $http service. But If you run this through a code minifier, it could change your code to this:

.controller('MyController', function (a) {

Now Angular doesn't know what a is, because it relies on the name of the variable to find the correct dependency. If you supply a string version of the dependency name, then Angular will be able to resolve it correctly even though $http was changed to a:

.controller('MyController', ['$http', function (a) {
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.