简体   繁体   English

如何在angularjs中的app.config中注入依赖项?

[英]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. 缩小AngularJS应用程序时出现错误,因为手动注入的依赖项无法按我期望的那样工作。 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). 这是因为app.config返回对应用程序的引用(用于链接)。 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/ http://jsfiddle.net/ADukg/3196/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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