我有一个带有工厂的模块。当程序启动并传递一个对象时,该工厂需要初始化为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);
});
这是一种更优雅的方式吗?
答案 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);
});