angularjs defining services for the same module in

2019-02-03 05:26发布

问题:

I have two files in which I define services in my angular app, but when I try to use them both in my directive, I get an error saying the service provider is not found for whichever directive I define second. It seems like one service is overwriting the other. If I change the module definition in service2.js to myapp.services2, then it works. I would think I could add multiple factories to the same module this way. Can someone point out what I'm doing incorrectly?

service1.js:

var services = angular.module('myapp.services',[]);
services.factory('Service1', function() {
    // service code
});

service2.js:

var services = angular.module('myapp.services',[]);
services.factory('Service2', function() {
    // service code
});

mydirective.js:

angular.module('myappdirective', []).directive('myapp', ['Service1', 'Service2',
function(service1,service2) {
    // directive code
}]);

回答1:

This is from the docs:

Beware that using angular.module('myModule', []) will create the module myModule and overwrite any existing module named myModule. Use angular.module('myModule') to retrieve an existing module.

Found here: https://docs.angularjs.org/guide/module



回答2:

This is possible, however will be error prone, hence not recommended

Make small modification to what you are already doing

Just do not re-declare the module variable in other files other than service1.js or put the module definition to a file of its own and include these JS file in the order of Module.js, services.js, directive.js then it will work