【问题标题】:AngularJS dependency injection of value inside of module.configAngularJS 依赖注入 module.config 中的值
【发布时间】:2012-10-15 20:19:17
【问题描述】:

尝试为模块设置一些辅助值。尝试了服务和价值,但没有帮助:

var finance = angular.module('finance', ['finance.services'])
    .value("helpers", {
        templatePath: function (name) {
            return '/areas/scripts/finance/templates/' + name + '/index.html';
        }
    })
    .config(['$routeProvider', 'helpers', function ($routeProvider, helpers) {
    $routeProvider.
        when('/', {
            templateUrl: helpers.getTemplatePath('dashboard'),
            controller: DashboardController
        })            
        .when('/people', {
            templateUrl: '/areas/scripts/app/people/index.html',
            controller: PeopleController
        })
        .otherwise({
            redirectTo: '/dashboard'
        });
}]);

我做错了什么?

【问题讨论】:

  • 那你怎么解决呢?

标签: angularjs


【解决方案1】:

问题是你试图在 AngularJS 模块的配置块中注入一个值对象helpers,这是不允许的。您只能在配置块中注入常量和提供程序。

AngularJS documentation(部分:“模块加载和依赖项”)提供了对此的见解:

模块是配置和运行块的集合 在引导过程中应用于应用程序。在其 该模块的最简单形式由两种块的集合组成:

配置块 - 在提供者注册期间执行 和配置阶段。只能注入提供者和常量 进入配置块。这是为了防止意外实例化 完全配置之前的服务。

运行积木 - 获取 在注入器创建后执行并用于启动 应用。只有实例和常量可以注入运行 块。这是为了防止在 应用程序运行时间。

【讨论】:

  • 其实我已经读过了,但我也太笨了,记不得了。谢谢。
【解决方案2】:

您可以使用.constant 代替.value。然后您可以在.config 部分使用您的服务。

【讨论】:

  • 正如 fedor.belov 所说,通过使用 .constant 设法让它在 1.0.6 中工作
【解决方案3】:

您的辅助方法称为templatePath,您在.config 中将其称为getTemplatePath。不应该是:

when('/', {
            templateUrl: helpers.templatePath('dashboard'),
            controller: DashboardController
     }) 

【讨论】:

    猜你喜欢
    • 2013-02-23
    • 1970-01-01
    • 1970-01-01
    • 2016-03-17
    • 2013-01-22
    • 2014-07-30
    • 1970-01-01
    • 2014-12-04
    • 2012-11-23
    相关资源
    最近更新 更多