2

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!

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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

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.