I am a Learner in angularJs. Today I read a difference between factory and service method in 'Novice to Ninja' of angular JS.
The statement is -
"Note that you return an object from the factory function, so you have the freedom to determine which object to return based on certain parameters. This is not the case with services where you simply pass a constructor function to service()."
So can anybody help me while creating such example in which I can return a customized object based on parameters.
Thanks in advance.
答案 0 :(得分:1)
已编辑添加提供商
var app = app.moudule("app", []);
app.provider('customeFactory', function(){
var type;
return {
setType: function(value){
type = value;
},
$get: function (){
if (type == "typeA"){
return {
type: 'TypeA was set:' + type;
}
}else {
return {
value: 'another type was set:' + type;
}
}
}
}
})
app.config(function(customeFactoryProvider){
customeFactoryProvider.setType("typeA");
})
以抽象方式表示
factory
返回对象,您必须根据需要自定义它,因为它描述了显示模块模式
var factoryFunc = function(){
var saveFunc = function(){ /* logic */ }
var updateFunc= function(){/* logic */ }
// this function not exposed since it not specified in the return object
var deleteFunc = function(){ /* */ }
var obj = {
save: saveFunc,
update: updateFunc
}
return obj;
}
// result now is the returned object {save, update}
var result = factoryFunc();
service
中的案例返回实例
var ServiceFunc = function () {
this.funcA = function() {}
this.funcB = function() {}
}
// result now is instance of ServiceFunc with all its functions A and B
var result = new ServiceFunc();