在使用之前初始化AngularJS中的注入模块

时间:2014-11-26 05:13:54

标签: angularjs

我有一个带有工厂的模块。当程序启动并传递一个对象时,该工厂需要初始化为ONCE。

目前,我这样做非常优雅。我包含模块,然后在我的主app.js的运行函数中,我调用工厂的初始化方法并将其传递给文件:

/* 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);
    }); 

这是一种更优雅的方式吗?

1 个答案:

答案 0 :(得分:1)

使用提供商。 可以在任何模块中配置提供程序,但一旦配置阶段完成,这些功能将不再可用。

/* 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);
    });