Difference between two ways of injecting modules in Angular

后端 未结 1 1324
离开以前
离开以前 2021-01-21 05:51

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

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

// VERSION 1

app.controller(\'         


        
相关标签:
1条回答
  • 2021-01-21 06:29

    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.

    0 讨论(0)
提交回复
热议问题