0

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?

1 Answer 1

1

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);
    }); 
Sign up to request clarification or add additional context in comments.

1 Comment

Fantastic. That's exactly what I want: configure once and then stop! I will vote this once the ticker runs out!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.