Factory
Using Factory is to create an object, add attributes to it, and then return the object. After you pass the service into the controller, the properties of the object in controller can be used by factory.
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
The Service is instantiated with the "new" keyword. Therefore, you should add attributes to "this" and the service returns "this". After you have sent the service into the controller, the attributes on "This" in controller can be used by the service.
App.controller (' Myfactoryctrl ', function ($scope, myservice) {
$scope. Artist = Myservice.getartis ();
});
App.service (' MyService ', function () {
var _artist = ';
This.getartist = function () {return
_artist;
}
});
Provider
Providers is the only service that you can pass into the. config () function. When you want to make a module-wide configuration before the service object is enabled, you should use 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, = this;
return {
getartist:function () {return
that._artist;
},
ThingOnConfig:that.thingFromConfig
}
}
});
App.config (function (myproviderprovider) {
Myproviderprovider.thingfromconfig = ' This is set in config () ';
});
Value and constant
$provide. Value (' myvalue ');
$provide. Constant (' myconstant ');
/* The difference between:
1. Value can be modified, constant once the declaration can not be modified
2. Value cannot be injected in config, constant can.
*/
The relationship between provider, factory and service
App.provider (' MyDate ', {
$get: function () {return
new Date ();
}
});
Can be written
as App.factory (' MyDate ', function () {return
new Date ();
});
Can be written
as App.service (' mydate ', Date);
Summarize
- All vendors are instantiated only once, and they are all single cases.
- In addition to constant, all suppliers can be decorated by adorners (decorator)
- Value is a simple, but injected,
- Service is an injection builder
- Factory is a method that can be injected.
- Decorator can modify or encapsulate other suppliers, except, of course, constant
- Provider is a configurable factory
The above is the Angularjs Provider, factory, service data collation, follow-up continue to supplement the relevant information, thank you for your support of this site!