简体   繁体   English

如何从另一个模块获取angular.js模块的值

[英]How to get angular.js module's value from another module

I have two modules in my angular.js app. 我的angular.js应用程序中有两个模块。 In module1 (example name) I have a value defined like 在module1(示例名称)中,我有一个定义的值

angular.module('module1')
    .value('ID', '')
    .service('someService', function(ID) {
        this.getId = function() {
            return ID;
        }
        this.setId = function(id) {
            ID = id;
        }
    })

I would like to access module1's ID value in module2. 我想在module2中访问module1的ID值。 I can access module1 from module2 using ` 我可以使用`来从module2访问module1

angular.module('module1')

log in console will be` 登录控制台将是`

Object {_invokeQueue: Array[39], _configBlocks: Array[1], _runBlocks: Array[1], requires: Array[8], name: "module1"}

when I try to access ID value or someService using 当我尝试访问ID值或someService时使用

angular.module('module1').service("someService");

or 要么

angular.module('module1').value("ID");

I am getting strange object looks like 我变得奇怪的对象看起来像

Object {_invokeQueue: Array[40], _configBlocks: Array[1], _runBlocks: Array[1], requires: Array[8], name: "module1"}

Also I can't include module1 in the module2 on initialization, using this style 此外,我无法在初始化时使用此样式在module2中包含module1

angular.module('module2', ['module1']);

because I already have module2 included in module1 因为我已经在module1中包含了module2

angular.module('module1', ['module2']);

You still need to inject it as a dependency as you would with a controller or service etc. 您仍然需要像控制器或服务等那样将其作为依赖项注入。

If you wanted to access it in a controller you could have code similar to this 如果您想在控制器中访问它,您可以使用与此类似的代码

angular.module('module2').controller('MyExistingCtrl', ['ID', function(ID){
    console.log(ID);
}]);

Or, following John Papa's styleguide: 或者,遵循John Papa的风格指南:

angular.module('module2').controller('MyExistingCtrl', MyExistingController)

MyExistingController.$inject = ['ID'];

function MyExistingController(ID){
    console.log(ID);
}

Read more on dependency injection . 阅读更多依赖注入

Also it is explained on the angular documentation for providers. 此外,它还提供了供应商的角度文档 Scroll down the "Value Recipe" section. 向下滚动“Value Recipe”部分。

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

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