【发布时间】:2015-08-03 04:36:11
【问题描述】:
我有两个第三方模块,都定义了一个同名的工厂。显然,我无法控制这些模块的命名,而无需求助于 kludge。
此外,我还有两个 internal 模块,每个模块都使用两个 third-party 模块中的一个作为依赖项(如下所示)。我确信我无法访问当前模块依赖项中未列出的模块中的组件,但事实证明我错了。
即使own1 依赖于thirdParty1(将hello 定义为hello world),它也会在控制器中获得hi there(来自thirdParty2)。其他模块对也是如此。
有没有办法“隔离”模块,这样我就只能使用我明确依赖的东西?如果没有,如果我可以随时访问任何内容(假设主应用程序模块将其作为其依赖项),那么拥有模块有什么意义?另外,如果我有两个模块,其中的组件名为 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
【问题讨论】:
-
您实际上有两个定义同名服务的库吗?模块用于封装特定行为并帮助测试您的应用程序。
-
模块服务于更多的结构和组织目的,而不是隔离。在引导时,所有模块都被打包到一个全局模块中,以便它们可以相互访问。
-
如果您尝试使用的两个库具有内部结构,通常您可以只包含您正在使用的部分。例如,如果你想要 AngularUI-Bootstrap 和 AngularStrap 的一部分,你可以选择你包含的模块。 (AngularStrap 有
mgcrea.ngStrap.modal,AngularUI-Bootstrap 有ui.bootstrap.modal)。通过仅包含您需要的部分,您可以确保从每个部分中获得正确的部分。 -
@NicholasThomson 就是这样!我正要摆脱其中一个,但这就是我被这东西咬得很厉害的地方。但是......即使我从第三方挑选子模块,如果它们仍然定义相同的组件,我还是会有命名冲突,不是吗?
-
我相信 Angular 会更喜欢第二个模块。因此,如果您只使用 AngularStrap 中的 $modal ,请尝试以下操作:
angular.module('app', ['ui-bootstrap', 'mcrea.ngStrap.modal']);
标签: javascript angularjs angularjs-module