【发布时间】:2012-11-04 14:24:02
【问题描述】:
考虑下面的 jfiddle http://jsfiddle.net/bchapman26/9uUBU/29/
//angular.js example for factory vs service
var app = angular.module('myApp', ['module1', 'module2']);
var service1module = angular.module('module1', []);
service1module.factory('myService', function() {
return {
sayHello: function(text) {
return "Service1 says \"Hello " + text + "\"";
},
sayGoodbye: function(text) {
return "Service1 says \"Goodbye " + text + "\"";
}
};
});
var service2module = angular.module('module2', []);
service2module.factory('myService', function() {
return {
sayHello: function(text) {
return "Service2 says \"Hello " + text + "\"";
},
sayGoodbye: function(text) {
return "Service2 says \"Goodbye " + text + "\"";
}
};
});
function HelloCtrl($scope, myService) {
$scope.fromService1 = myService.sayHello("World");
}
function GoodbyeCtrl($scope, myService) {
$scope.fromService2 = myService.sayGoodbye("World");
}
我有 2 个模块(模块 1 和模块 2)。 module1 和 module2 都定义了一个名为 myService 的服务。当两个模块都导入 myApp 时,这似乎会在 Angular 中的 myService 上产生名称冲突。看来 AngularJs 只是使用了第二个服务定义,而没有警告您可能存在的问题。
非常大的项目(或通常只是重用模块)会有名称冲突的风险,这可能难以调试。
有没有办法给模块名称加上前缀,这样就不会发生名称冲突?
【问题讨论】:
-
更新:我发现了一种可能的解决方法,方法是对传递到 di 系统的服务名称应用命名约定。见jsfiddle.net/bchapman26/9uUBU/32 但是,我的主要问题仍然存在:有没有一种本地方法可以避免上面显示的名称冲突?
-
现在这似乎是个问题,尤其是当您考虑使用 3rd 方组件的潜在用途时。我有一个问题提出here。
-
我认为这不是问题(实际上是一个功能和设计),因为它对于测试和覆盖行为很有用。命名空间或使用命名约定是要走的路。
标签: angularjs namespaces collision angularjs-module