angularjs defining services for the same module in different files

Jeff Storey picture Jeff Storey · Apr 30, 2014 · Viewed 16.5k times · Source

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
}]);

Answer

aet picture aet · Apr 30, 2014

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