【问题标题】:How to get angular.js module's value from another module如何从另一个模块获取 angularjs 模块值
【发布时间】:2016-09-30 11:59:24
【问题描述】:

我的 angular.js 应用程序中有两个模块。 在 module1(示例名称)中,我定义了一个值,例如

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

我想在模块 2 中访问模块 1 的 ID 值。 我可以使用从 module2 访问 module1 `

angular.module('module1')

登录控制台会是`

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

当我尝试使用

访问 ID 值或 someService
angular.module('module1').service("someService");

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

我发现奇怪的物体看起来像

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

我也不能在初始化时在 module2 中包含 module1,使用这种样式

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

因为我已经在 module1 中包含了 module2

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

【问题讨论】:

  • 两个模块中是否存在相同的 ID 值?
  • @MathewBerg 只存在于module1中
  • 那么,如果您在 module1 中包含了 module2,您应该可以将其 DI 插入其中。
  • @MathewBerg 你能解释的更详细些吗

标签: javascript angularjs angular-services angular-module


【解决方案1】:

您仍然需要像使用控制器或服务等一样将其作为依赖项注入。

如果您想在控制器中访问它,您可以使用类似于此的代码

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

或者,按照 John Papa 的风格指南:

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

MyExistingController.$inject = ['ID'];

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

阅读更多dependency injection

angular documentation 上也为供应商提供了解释。向下滚动“价值配方”部分。

【讨论】:

  • 嗨,马特,感谢您的回答。据我了解,如果我需要访问模块 2 现有控制器中的“ID”值,您的代码将在模块 1 内创建一个新控制器。
  • @styopdev 好吧,这只是示例语法。只需交换模块和控制器名称即可满足您的需求。你只是在注射,就像你注射其他任何东西一样。我会编辑。
  • 成功了,谢谢帮助!我无法想象解决方案如此明显,并且可以在控制器中注入其他模块的价值。
  • @styopdev 没问题,很高兴为您提供帮助!只要将模块作为依赖项包含在内,您就可以在任何地方注入它的所有值、服务、常量等。这是第三方模块如何工作的基础。包含模块 -> 访问所有服务。
猜你喜欢
  • 1970-01-01
  • 2012-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-05
  • 2016-08-28
  • 2020-11-24
相关资源
最近更新 更多