0

I have been reading AngularJS code and trying to make sense out of the argument passed to the .config method. From the sample below, it appears to be passing [ ] to .config. The part that perplexes me is that according to angular.Module documentation on docs.angularjs.org, the method config, takes configFn as a parameter which is a function. So why in following example I see that ['$routeProvider', function(..) { .. }] being passed as the argument? Can someone help clarify my confusion?

var sampleApp = angular.module('phonecatApp', []);

sampleApp .config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/addOrder', {
        templateUrl: 'templates/add-order.html',
        controller: 'AddOrderController'
      }).
      when('/showOrders', {
        templateUrl: 'templates/show-orders.html',
        controller: 'ShowOrdersController'
      }).
      otherwise({
        redirectTo: '/addOrder'
      });
  }]);
2
  • Read about dependency annotations: docs.angularjs.org/guide/di#dependency-annotation Short answer: since minifiers renames the function parameters names, you can use array to tell Angular what service in what order should be injected (minifiers don't rename array elements strings). Commented Nov 16, 2014 at 8:05
  • And you shouldn't be doing this by hand. If you run a minification process in a task runner (gulp/grunt) then you could add the annotations in the same task. Look into ng-annotate Commented Nov 16, 2014 at 8:20

2 Answers 2

3

The array notation is used in order to avoid problems with the injected modules when minificate the js files for production. Since the strings don't be minificated, passing the '$routeProvider' as a string in the array is a convention in Angularjs.

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

Comments

0

You would have the same result if you didn't pass the string parameter and only passed the function. The code would work but you would have problems when you tried to minify your application.

A minifier will rename the parameters of a function so Angular would have no way to understand what your dependency is.

You solve this by passing an array with the names of the parameters in the same order the function expects them.

This is happening not only in the config function but everywhere you need to inject dependencies.

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.