简体   繁体   中英

How to inject dependencies in app.config in angularjs?

I've been getting errors when minifying my AngularJS app because manually injected dependencies aren't working how I'd expect. The following didn't work:

var config = app.config(function($routeProvider) {
    $routeProvider
        .when('/', {controller: 'PageCtrl', templateUrl: '../templates/home.html'});
        .otherwise({redirectTo: '/'});
});
config.$inject = ['$routeProvider'];

The only thing that worked is:

app.config(['$routeProvider', function($routeProvider) {
    ...
}]);

Why does the first dependency injection technique work for controllers but not configs?

It is because app.config returns reference to the app (for chaining). This code works:

var config = function($routeProvider) {
    $routeProvider
        .when('/', {controller: 'PageCtrl', templateUrl: '../templates/home.html'})
        .otherwise({redirectTo: '/'});
};

config.$inject = ['$routeProvider'];
app.config(config);

http://jsfiddle.net/ADukg/3196/

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