简体   繁体   中英

Difference between two ways of injecting modules in Angular

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM