javascript - AngularJS - 模块依赖,命名冲突

标签 javascript angularjs angularjs-module

我有两个第三方 模块,它们都定义了同名的工厂。显然,如果不借助杂乱无章,我无法控制这些模块的命名。

此外,我还有两个内部 模块,每个模块使用两个第三方 模块中的不同模块作为依赖项(如下所示)。我确信我无法访问当前模块依赖项中未列出的模块中的组件,但事实证明我错了。

这里就算own1取决于 thirdParty1 (它有 hello 定义为 hello world )它得到 hi there (来自 thirdParty2)在 Controller 中。其他模块对也是如此。

有什么方法可以“隔离”模块,以便我只能使用我明确依赖的东西吗?如果没有,如果我可以随时访问任何内容(假设主应用程序模块将其作为依赖项),那么拥有模块有什么意义?另外,如果我有两个模块,其组件名为 hello我怎么知道要使用哪个?

这是 http://jsbin.com/vapuye/3/edit?html,js,output 的 jsbin

angular.module('app', ['own1', 'own2']);

//third-party modules
angular.module('thirdParty1', []).factory('hello', function () {
  return 'hello world';
});

angular.module('thirdParty2', []).factory('hello', function () {
  return 'hi there';
});

// "own" modules
angular.module('own1', ['thirdParty1']).controller('Own1Ctrl', function(hello) {
  this.greet = hello;
});

angular.module('own2', ['thirdParty2']).controller('Own2Ctrl', function(hello) {
  this.greet = hello;
});

结果是:

<body ng-app="app">
  <div ng-controller="Own1Ctrl as own1">
    Own1: {{ own1.greet }}
  </div>
  <div ng-controller="Own2Ctrl as own2">
    Own2: {{ own2.greet }}
  </div>
</body>

是:

Own1: hi there
Own2: hi there

最佳答案

您可以显式请求某个模块的工厂(无需依赖注入(inject)):

var injector = angular.injector(['thirdParty1']);
var hello1 = injector.get('hello');

var injector = angular.injector(['thirdParty2']);
var hello2 = injector.get('hello');

您也可以使用它,将第三方工厂包装成自己的工厂:

angular.module('own1', ['thirdParty1']).factory('hello1', function () {
  var injector = angular.injector(['thirdParty1']);
  var hello = injector.get('hello');
  return hello;
});

angular.module('own2', ['thirdParty2']).factory('hello2', function () {
  var injector = angular.injector(['thirdParty2']);
  var hello = injector.get('hello');
  return hello;
});

这允许您在应用程序的所有其他部分使用 hello1hello2

关于javascript - AngularJS - 模块依赖,命名冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30374934/

相关文章:

angularjs - 模拟过滤器中使用的服务

css - 如何在angularjs中添加和删除类

javascript - Vanilla AngularJs 未加载。

javascript - 使用 d3.legend 进行强制布局上的交互式图例

javascript - 使用 jQuery 取消选中子复选框时如何取消选择父复选框?

javascript - 如何使用 pdfmake 在标题中的 Canvas 顶部添加图像?

javascript - 使用来自 ui-bootstrap 的 tabset 指令时,Angularjs Routing 行为异常

angularjs-module - Angular JS的电子表格模块

javascript - 交换 AngularJS 语法导致错误

javascript - 为什么这个片段不起作用?