1

Quoted from the Angular tutorial:

To use a service in Angular, you simply declare the names of the dependencies you need as arguments to the controller's constructor function, as follows:

phonecatApp.controller('PhoneListCtrl', function ($scope, $http) {...}

It seems that the controller method is checking which services you've requested by looking at the argument names, such as $scope and $http. But that seems so crude. Is it actually just converting the function to a string and slicing it, like this? Or is there some cleverer behind-the-scenes action going on?

How does it know which services your controller requested?

Community
  • 1
  • 1
temporary_user_name
  • 35,956
  • 47
  • 141
  • 220

1 Answers1

3

You are correct. Angular just looks at the argument names. This causes problems with minification because minification could convert function ($scope, $http) to function (a, b) and then angular won't know which is what.

Instead you should use the long syntax:

phonecatApp.controller('PhoneListCtrl', ['$scope', '$http', function ($scope, $http) {...}

In terms of how it works. Angularjs makes clever use of the fact that every object in JavaScript has a toString function to parse and extract the names of the parameters before deciding what arguments to call your controller function with. This page has some more detail about it: http://www.alexrothenberg.com/2013/02/11/the-magic-behind-angularjs-dependency-injection.html

temporary_user_name
  • 35,956
  • 47
  • 141
  • 220
Wayne Ellery
  • 7,888
  • 1
  • 28
  • 45
  • You don't need to use the long syntax. It's ugly and hard to maintain. See ngannotate as a tool to inject the long syntax when building the js. https://github.com/olov/ng-annotate – Peter Ashwell Jan 04 '15 at 07:09
  • 1
    @PeterAshwell That's correct, that you don't need to if using ng-annotate. I don't agree that it's ugly. It's slightly harder to maintain but not much. – Wayne Ellery Jan 04 '15 at 07:15