Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: Share factory between multiple modules

Let's say I have a module called App which injects 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 holds all factories:

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

And the controllers module holds all 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.
});

The actual Question:

Why does the "someKickstartValue" not apply to the controllers? As far as I do understand the module app has it's own testFactory instance and the module controllers has it's own as well, so there can't be any information shared between modules via factories. Is there a way around, or have I made a mistake?

like image 646
tmuecksch Avatar asked Feb 06 '14 09:02

tmuecksch


2 Answers

I fixed it by removing the "factories" dependency of the controller.

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

Because I now do not declare factories as dependency, the controllers module doesn't create it's own instance of factories and has access to the instance of the app module which injects the controllers module.

like image 107
tmuecksch Avatar answered Nov 09 '22 19:11

tmuecksch


I faced the same problem. I solved it in the following way:

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

Such structure allows to use factories, services, directives attached to the shared module in other modules.

like image 31
Pavel Shkleinik Avatar answered Nov 09 '22 21:11

Pavel Shkleinik