3

What's the difference between these two ways of loading modules in AngularJS:

var app = angular.module('app', ['ngRoute']);

// VERSION 1

app.controller('HomeCtrl', ['$scope', '$dep1', '$dep2', function($scope, $dep1, $dep2) {
    // controller code
}];

// VERSION 2

function HomeCtrl($scope, $dep1, $dep2){
    // controller code
}
HomeCtrl.$inject=['$scope', '$dep1', '$dep2'];
return HomeCtrl;

// Then load in the controller into the app module
app.controller('HomeCtrl', HomeCtrl);
3
  • 1
    The first one is minification safe. You can concatenate your script and it will still work. This is because the names of your injected services won't be cut. The second one is a slightly more verbose way of doing this. Commented Feb 9, 2015 at 13:16
  • 1
    @DonaldSupertramp Both are minification safe Commented Feb 9, 2015 at 13:28
  • @WayneEllery that's why I wrote: "The second one is a slightly more verbose way of doing this" Commented Feb 9, 2015 at 13:36

1 Answer 1

2

Both ways are for minification safe dependency injection. Here is an abstract from source code, injector.js file:

if (typeof fn === 'function') {
    if (!($inject = fn.$inject)) {
        $inject = [];

        // convert function to string, parse arguments

        fn.$inject = $inject;
    }
} else if (isArray(fn)) {
    last = fn.length - 1;
    assertArgFn(fn[last], 'fn');
    $inject = fn.slice(0, last);
} else {
    assertArgFn(fn, 'fn', true);
}
return $inject;

Above code explains very well that if function you are injecting dependencies into, has type of

  1. function

Angular checks if this functio has property $inject and if so here is resulting array of services to inject.

  1. array

Angular takes values from this array leaving out the last element, which is supposed to be an actual function to inject value into.

Note the part I denoted as comment // convert function to string, parse arguments. In case if there is no $inject property is configured and provided controller/service/etc. is actually of a function type, then Angular will take string representation of the function and parse literally defined parameters it accepts. Then obtained array of parameters will be used as services to inject.

So as you can see the difference is very minor.

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

2 Comments

Sorry I'm still unclear what the difference between the two is. The reason I ask is because I want to wrap the modules inside requirejs e.g. define([], function() { // code }); and I'm seen version 2 used when used inside requirejs rather than version 1 (the usual seen on Angular Docs).
You can use the one you like more, they both yield the same result.

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.