factory
用 Factory 就是創(chuàng)建一個對象儒溉,為它添加屬性尚镰,然后把這個對象返回出來抖僵。你把 service 傳進(jìn) controller 之后椎木,在 controller 里這個對象里的屬性就可以通過 factory 使用了窄驹。
You should use $provide.factory(getFn) if you do not need to configure your service in aprovider.
app.controller('myFactoryCtrl', function($scope, myFactory){
$scope.artist = myFactory.getArtis();
});
app.factory('myFactory', function(){
var _artist = '';
var service = {};
service.getArtist = function(){
return _artist;
}
return service;
});
service
Service 是用"new"關(guān)鍵字實(shí)例化的朝卒。因此,你應(yīng)該給"this"添加屬性乐埠,然后 service 返回"this"抗斤。你把 service 傳進(jìn) controller 之后囚企,在controller里 "this" 上的屬性就可以通過 service 來使用了。
You should use $provide.service(class) if you define your service as a type/class.
app.controller('myFactoryCtrl', function($scope, myService){
$scope.artist = myService.getArtis();
});
app.service('myService', function(){
var _artist ='';
this.getArtist = function(){
return _artist;
}
});
provider
Providers 是唯一一種你可以傳進(jìn) .config() 函數(shù)的 service瑞眼。當(dāng)你想要在 service 對象啟用之前龙宏,先進(jìn)行模塊范圍的配置,那就應(yīng)該用 provider伤疙。
app.controller('myProviderCtrl', function($scope, myProvider){
$scope.artist = myProvider.getArtist();
$scope.data.thingFromConfig = myProvider.thingOnConfig;
});
app.provider('myProvider', function(){
this._artist = '';
this.thingFromConfig = '';
this.$get = function(){
var that = this;
return {
getArtist: function(){
return that._artist;
},
thingOnConfig: that.thingFromConfig
}
}
});
app.config(function(myProviderProvider){
myProviderProvider.thingFromConfig = 'This was set in config()';
});
value和constant
$provide.value('myValue', 10);
$provide.constant('myConstant', 10);
/*
二者的區(qū)別:
1. value可以被修改银酗,constant一旦聲明就無法修改
2. value不可以在config中注入,constant可以徒像。
*/
provider黍特、factory、service三者的關(guān)系
app.provider('myDate', {
$get: function() {
return new Date();
}
});
//可以寫成
app.factory('myDate', function(){
return new Date();
});
//可以寫成
app.service('myDate', Date);
總結(jié)
- 所有的供應(yīng)商都只被實(shí)例化一次厨姚,也就說他們都是單例的
- 除了constant衅澈,所有的供應(yīng)商都可以被裝飾器(decorator)裝飾
- value就是一個簡單的可注入的值
- service是一個可注入的構(gòu)造器
- factory是一個可注入的方法
- decorator可以修改或封裝其他的供應(yīng)商,當(dāng)然除了constant
- provider是一個可配置的factory