First of all, what is the service of this thing for? Most of the time we put too much data and logic in the controller, peremptorily. This way our controller turns out to be bloated. From their life cycle can be found, in fact, the controller should be initialized when needed, not directly discarded, free memory. Therefore, when we switch or refresh the page, angular will empty the current controller. As a result, the service should be used to store the application business logic and persisted data, and the data can be applied between different controllers.
So the question comes, (learn excavator to find Lanxiang) Angular provides three ways to create and register our service:factory, service and provider.
Factory:
- The
- uses factory to create an object, add attributes to it, and then return the object. When you pass the service into the controller, the object's properties can be used by factory in the controller.
- var app = Angular.module (' app ', []);
- app.factory (' MyFactory ', function () {
- var test = {};
- Test.name = "Jason";
- Test.sayhello = function () {Console.log ("Hello World")};
- return test;
- });
-
- app.controller ("Myctrl", Function ($scope, myfactory) {
$scope. Greet =myfactory.test.sayhello;
//use The attrs of the obj in the factory
- })
- This is probably the use of factory.
- Service:
- The service is instantiated with the new keyword. Therefore, you should add a property to this and then the service returns this. After you pass the service into the controller, the properties on this in the controller can be used through the service.
- App.service (' MyService ', function () {
var _artist = "Nelly";
This.getaritist = function () {
return _artist;
}
});
App.controller ("Myctrl", Function ($scope, MyService) {
$scope. getartist = myservice.getartist;
});
- 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.provider ("MyProvider", function () {
this._artist = "";
This.thingfromconfig = "";
this. $get = function () {
var. = this;
return {
getartist:function () {
& nbsp return that._artist;
},
thingonconfig:that.thingfromconfig
&N Bsp }
},
thingonconfig
});
App.controller ("Mycontroller", Function ($scope, myProvider) {
$scope. Artist = Myprovider.getartist ();
$scope. data.thingfromconfig = Myprovider.thingonconfig;
});
App. Config (function (myproviderprovider) {
Myproviderprovider.thingfromconfig = "This is set in config () ";
})
AngularJS Note Creation Service comparison: Factory vs Service vs Provider.