AngularJS: factory share between multiple modules

Let's say I have a module called App that introduces two other modules called factories and controllers:

var app = angular.module("app", ["factories", "controllers", "directives"]) .run(function ($rootScope, userFactory) { userFactory.property = "someKickstartValue"; }); 

The factories module contains all the plants:

 var factories = angular.module("factories", []), factory = factories.factory("testFactory", { property: "someValue" }); 

And the controller module contains all the controllers:

 var controllers = angular.module("controllers", ["factories"]), controller = controllers.controller("controller", function ($scope, testFactory) { console.log(testFactory.property); // Returns "Some Value" and not // "someKickstartValue" as expected. }); 

Actual question:

Why doesn't "someKickstartValue" apply to controllers? As far as I understand, a modular application has its own instance of testFactory, and module controllers have its own, so there can be no information shared between modules through factories. Is there a way, or have I made a mistake?

+6
source share
2 answers

I fixed it by removing the β€œfactory” dependency on the controller.

 var controllers = angular.module("controllers", []), controller = controllers.controller("controller", function ($scope, testFactory) { console.log(testFactory.property); // Returns "someKickstartValue" as expected }); 

Since I no longer declare factories as dependencies, the controller module does not create its own instance of the factories and has access to the application module instance that introduces the controller module.

+6
source

I ran into the same problem. I solved it as follows:

 // modules.js (function (angular) { angular.module("shared", []); angular.module("user", ["shared"]); angular.module("admin", ["shared"]); })(window.angular); 

This structure allows the use of factories, services, directives attached to a common module in other modules.

+3
source

All Articles