Kousha
Kousha

Reputation: 36189

Initialize an injected module in AngularJS before using

I have a module with a factory inside it. This factory needs to be initialized ONCE when the program is booted and be passed an object.

Currently, I do this very none-elegantly. I include the module, and then in the run function of my main app.js, I call an initialization method of the factory and pass it the file:

/* The to be imported module */
angular
    .module('myModule', [])
    .factory('myFactory', function () {
        var setting = null;

        var myFactory = {
            initialize : initialize,
            action1 : action1,
            ...
        };

        return myFactory;

        function initialize(obj) {
            if (typeof setting == null) {
                setting = obj;
            }
        }
    });

/* Main app */
angular
    .module('myApp', ['myModule'])
    .app(function(myFactory) {
        myFactory.initialize(someFile);
    }); 

What's a more elegant way of doing this?

Upvotes: 0

Views: 509

Answers (1)

Enzey
Enzey

Reputation: 5254

Use a Provider. The provider can be configured in any modules but once the configuration phase is complete those function are no longer available.

/* The to be imported module */
angular
    .module('myModule', [])
    .provider('myThingy', function () {
        var setting = null;

        var services = {
            initialize : initialize,
            action1 : action1,
            ...
        };

        // Only these services are available on the injected 'myThingy'
        this.$get = function() {
            return services;
        };

        // This function is only available to the config and other providers as 'myThingyProvider'.
        this.initialize = function+(obj) {
            if (typeof setting == null) {
                setting = obj;
            }
        }
    });

/* Main app */
angular
    .module('myApp', ['myModule'])
    // Yes, the appended 'Provider' is needed as it is a differnet object without it.
    .config(function(myThingyProvider) {
        myThingyProvider.initialize(someFile);
    }); 

Upvotes: 1

Related Questions