2

Please see my proof of concept: http://plnkr.co/edit/y3pzFv?p=preview.

How Do I configure Provider between 2 modules?

Brief: I am trying to generalize a service and configure multiple instances slightly differently.

Right now I have a bunch of Angular Services (factory) that I would like to generalize so they can be re-used. In my proof of concept I am trying to breakup an AngularJS 1.3 App into 2 modules 'bob' and 'joe'. Each module should share a Provider that should have a configurable variable called food. I am trying to define a re-usable service and create a separate instance for each module.

I have read the Angular documentation about Providers, and from what I understand providers allow you to extract the configurable part into the .config(). What am I doing wrong? I would expect Bob's Food to be Banana, but Joe's Food which is configured second is overwriting Bob's Food. This leads me to believe the Food provider is not creating a new instance for each of the 'bob' and 'joe' modules.

I'm on AngularJS v1.3.15

index.html

<div ng-controller="BobCtrl">Bob's Food: {{ providerInstance.get() }}</div>
<div ng-controller="JoeCtrl">Joe's Food: {{ providerInstance.get() }}</div>

app.js

angular.module('shared').provider('Food', function() {
  var _food = 'Default';  
  this.set = function(food) { _food = food; }

  this.$get = function() {
    return {
      get: function()  {
        return _food;
      }
    }
  };
});

angular.module('bob').config(function(FoodProvider) { 
  FoodProvider.set('Banana');
});
angular.module('bob').controller('BobCtrl', function($scope, Food) {
  $scope.providerInstance = Food;
});

angular.module('joe').config(function(FoodProvider) {
  FoodProvider.set('Apple');
});
angular.module('joe').controller('JoeCtrl', function($scope, Food) {
  $scope.providerInstance = Food;
});
user12121234
  • 2,519
  • 2
  • 25
  • 27
  • 1
    Ultimately when the app is bootstrapped there will be only one instance of provider and it is loaded just once, not for each submodules. [This answer might be able to clarify some stuffs](http://stackoverflow.com/questions/30653248/are-dependencies-shared/30653736#30653736). If you were to place `joe` before `bob` in the dependency list you will see `banana` that is because config of each of those sub modules are run in the order in which they are registered and one overrides another. You can store this as KVP like this. http://plnkr.co/edit/z2ACAr?p=preview – PSL Jun 15 '15 at 23:26
  • Possible duplicate of [Angularjs provider with different configurations in different modules](http://stackoverflow.com/questions/30002538/angularjs-provider-with-different-configurations-in-different-modules) – Paul Sweatte Dec 30 '15 at 06:14

1 Answers1

0

Because All types of Angular providers are singleton objects. The latest state of the provider object will be used when you try to refer them.

pranay kumar
  • 404
  • 3
  • 8