我在哪里可以初始化模块范围的变量?

时间:2022-09-10 17:52:50

I'm trying to do something like this:

我正在尝试做这样的事情:

angular.module('MyModule', ['ui'])
    .config(function($rootScope) {
        $rootScope.Gender = {
            'M': 'Male',
            'F': 'Female',
            'U': 'Unknown',
        };
    })

But I get this error:

但我得到这个错误:

Uncaught Error: Unknown provider: $rootScope from MyModule

未捕获错误:未知提供者:来自MyModule的$ rootScope

If I can't access $rootScope inside my module config, where's the proper place to initialize module-wide variables?

如果我无法在我的模块配置中访问$ rootScope,那么初始化模块范围变量的适当位置在哪里?

2 个解决方案

#1


8  

You can't inject services (here $rootScope) into config block. Only constants and providers can be injected during the config phase.

你不能将服务(这里是$ rootScope)注入配置块。在配置阶段只能注入常量和提供程序。

In your case the correct solution would be to use the run block. Just change config to run and things should be working as expected.

在您的情况下,正确的解决方案是使用运行块。只需更改配置即可运行,事情应按预期工作。

#2


25  

Instead of using $rootScope, you could also use an angular constant or value:

您也可以使用角度常量或值,而不是使用$ rootScope:

angular.module('MyModule', ['ui']).constant( 'Gender', {
  'M': 'Male',
  'F': 'Female',
  'U': 'Unknown',
});

A constant can never be changed, whereas a value can. And you can inject it wherever you need it:

常量永远不会改变,而值可以。您可以在任何需要的地方注入它:

app.controller( 'MainController', function ( $scope, Gender ) {
  console.log( Gender.M );
});

In my opinion. this seems more "proper" for site-wide variables than using $rootScope.

我的想法是。对于站点范围的变量来说,这似乎比使用$ rootScope更“合适”。

#1


8  

You can't inject services (here $rootScope) into config block. Only constants and providers can be injected during the config phase.

你不能将服务(这里是$ rootScope)注入配置块。在配置阶段只能注入常量和提供程序。

In your case the correct solution would be to use the run block. Just change config to run and things should be working as expected.

在您的情况下,正确的解决方案是使用运行块。只需更改配置即可运行,事情应按预期工作。

#2


25  

Instead of using $rootScope, you could also use an angular constant or value:

您也可以使用角度常量或值,而不是使用$ rootScope:

angular.module('MyModule', ['ui']).constant( 'Gender', {
  'M': 'Male',
  'F': 'Female',
  'U': 'Unknown',
});

A constant can never be changed, whereas a value can. And you can inject it wherever you need it:

常量永远不会改变,而值可以。您可以在任何需要的地方注入它:

app.controller( 'MainController', function ( $scope, Gender ) {
  console.log( Gender.M );
});

In my opinion. this seems more "proper" for site-wide variables than using $rootScope.

我的想法是。对于站点范围的变量来说,这似乎比使用$ rootScope更“合适”。