Search code examples
javascriptangularjsangularjs-serviceangularjs-module

How use shared services with controllers that use no shared services?


Assume there is a module with only one factory (the shared service).

angular.module('sharedService', [])
    .factory('sharedSrv', sharedService)

function sharedService() {
  var number;

  return {
    getNum: getNumber
  };

  function getNumber() {
    return number;
  }

  function setNumber(i) {
    number = i;
  }
}

I saw we can inject shared services by passing a dependency into module

angular.module('app', ['sharedService'])
.controller('theCtrl', function(sharedSrv) {
  var self = this;

  self.setSharedNumber = sharedSrv.setNumber;
}

However, How inject a shared service if controller use services from his own module?

angular.module('app', ['sharedService'])
.controller('theCtrl', theCtrlFun)
.service('theSrv', theSrvFun)

theCtrlFun.$inject = ['theSrv']

function theCtrlFun(localSrv) {
 // How call sharedService ? 
}

function theSrvFun() {
  // Some fantastic features.
}

Thank you for your help.


Solution

  • You shouldn't be injecting service module as variable, you need to pass the name of module as string

    angular.module('app', [sharedService])
    .controller('theCtrl', function(sharedSrv) {
    

    should be

    angular.module('app', ['sharedService'])
    .controller('theCtrl', function(sharedSrv) {
    

    OR you could follow Inline Array annotation of DI

    angular.module('app', ['sharedService'])
    .controller('theCtrl', ["sharedSrv",  function(sharedSrv) {
        //code here
    }]);