0

I see in the angular documentation for creating services that a service is created by definining a factory on a module.

However I need to define a common service for use across multiple modules. I am not seeing any thing in the documentation for that. Can it be done? Or is there some way to access a service from a module other than the module it was created on?

Victor Grazi
  • 15,563
  • 14
  • 61
  • 94

2 Answers2

2

Please check working demo: JSFiddle.

Define a service in some common module like:

angular.module('mySharedModule', [])
     .service('mySharedService',...

Then in other modules, use

angular.module('myModule', ['mySharedModule'])
    .controller('mySharedService', function (mySharedService) {
    ...

Then you can use mySharedService inside the module myModule. Your service is now injectable to it.

Joy
  • 9,430
  • 11
  • 44
  • 95
  • When you say .service did you mean .factory? – Victor Grazi Aug 03 '15 at 15:45
  • Oh, `service` and `factory` are both `providers`. In some sense they are for the same purpose. Please check http://stackoverflow.com/questions/15666048/service-vs-provider-vs-factory – Joy Aug 03 '15 at 15:48
  • This does not seem to work. I have in one JS file the module angular.module("treeApp") .controller("treeCtrl", function($scope, ... Then in another JS I define a factory service called Tags (the shared service) on that module with angular.module("treeApp").factory("Tags", function($http) ... Finally I have a new module called exportApp I want to refer to Tags. I define it like angular.module("exportApp", ["treeApp"]).controller("exportCtrl", ["Tags", function(Tags){}]. But I am getting uncaught errors – Victor Grazi Aug 03 '15 at 15:59
  • Your fiddle works as is, but when I replace service with factory it doesn't. Mine are defined as factory. Is there any way to get it to work with factory? – Victor Grazi Aug 03 '15 at 16:23
  • http://jsfiddle.net/vu7has2h/2/. Just the syntax difference. I think you can try some examples of service/factory first. – Joy Aug 03 '15 at 16:29
  • That worked, thanks. (Corporate proxy prevents me from going to chat, so I will say a public thanks!) – Victor Grazi Aug 03 '15 at 16:55
1

A service has to belong to a module. However, to use it in other modules, just include the owning module in the modules where you would like to use it. Example:

angular.module('common', [])
    .factory('yourService', ...);

angular.module('yourModule', ['common'])
    .controller('yourController', ['yourService', function(yourService) {
       // common service available here.
    }]);
GPicazo
  • 6,516
  • 3
  • 21
  • 24