Delve into angularjs--Custom service details (factory, service, provider)

Source: Internet
Author: User

Objective
    1. 3 ways to create custom services.
      1. Factory
      2. Service
      3. Provider
    2. As you should know, Angularjs is the backstage staff in the work outside the invention, he mainly applied the background of long-existing layered thinking. So we have to understand the role of the next layer, if you are the front-end people do not understand what is layered, then you'd better ask your backstage partner.
      DAO Layer: Is the model layer, in the background, the role of this layer is to write and database interaction data layer, in the ANGULARJS is mainly written Ajax.
      Service layer: The main write logic code, but in the ANGULARJS can also persist data (as a data container), for different controller high.
      Controller layer: That is, the control layer, in the ANGULARJS is written controllers. In the controller, try not to write the unnecessary logic, as far as possible in the service layer.
      So there are three ways to create a custom service.
Factory

A service created by the factory method is the function of returning an object with a property that has a method. Equivalent: var f = myfactory ();

<! DOCTYPE html><Html><Head><Metacharset="Utf-8" ><ScriptSrc="Http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js" ></Script></Head><Body><Divng-app="MyApp"Ng-controller="Myctrl" ><P>{{R}}</P></Div><Script> Create a modelvar app = Angular.module (' MyApp ', []);Create custom service App.factory with Factory mode (' MyFactory ',function() {var service = {};Define an object ' Service.name ="Zhang San";var age;Define a variable for privatizationWrite getter and Setter methods on private properties Service.setage =function (newAge) {age = NewAge;} Service.getage = function () { Span class= "Hljs-keyword" >return age; } return service; //Returns the object}); //Create controller App.controller ( ' Myctrl ', function ($scope, myFactory) { Myfactory.setage (20); $scope. R =myfactory.getage (); alert (myfactory.name);}); </script></ body></HTML>    

The service sample is injected into the custom service, but cannot be injected into the $scope scope object.

<script>var app = Angular.module (' MyApp ', []); App.factory (' MyFactory ',function($http,$Q) {var service = {}; Service.name ="Zhang San";Request Data Service.getdata =function(){var d =$q. Defer ();$http. Get ("url")function to read data: Success (function(response) {d.resolve (response);}) . Error (function () {D.reject ( "error"); }); return d.promise;} return Service;}); App.controller ( ' Myctrl ',  Function ( $scope, myfactory) {// alert (myfactory.name); Myfactory.getdata (). Then (function function (data) { Alert (data) //error when walking here}); }); </script>              
Service

Creating a custom service by service means an object of new: var s = new MyService (), which can be called in the controller as long as the property and method are added to this.

<Divng-app="MyApp"Ng-controller="Myctrl" ><H1>{{R}}</H1></Div><Script> var app = Angular.module (' MyApp ', []); App.service (' MyService ',function($http, $q) {THIS.name ="Service";This.myfunc =function(x) {Return x.tostring (16);16 binary}This.getdata =function(){var d = $q. Defer (); $http. Get ("URSL")function to read data: Success (function(response) {d.resolve (response);}) . Error (function () {alert (0" D.reject ( "error");}); return d.promise;} }); App.controller ( ' Myctrl ',  Function255); Myservice.getdata (). Then (function function (data) { Alert (data) //error when walking here}); }); </SCRIPT>         
3.provder

Only Provder is a service that can pass the. config () function. If you want to make a module-wide configuration before the service object is enabled, you should choose Provider. It is important to note that when injecting Provider into the config function, the name should be: Providername+provider.
The advantage of using provider is that you can modify the provider object in the App. config function before passing it to other parts of the application.
When you create a service using provider, the only properties and methods that can be accessed in your controller are the content returned through the $get () function.

<Body><Divng-app="MyApp"Ng-controller="Myctrl" ></Div><Script> var app = Angular.module (' MyApp ', []);It is important to note that when injecting Provider, the name should be: Providername+provider App. Config (function(Myproviderprovider) {Myproviderprovider.setname ("The Holy Sage"); }); App.provider (' MyProvider ',function() {var name="";var test={"A":1,"B":2};Note that the setter method must be (set+ variable first letter capitalization) formatThis.setname =function(NewName) {name = NewName}this. $get =function($http, $q) {return {getData:function(){var d = $q. Defer (); $http. Get ("url")function to read data: Success (function(response) {d.resolve (response);}) . Error (function() {D.reject ("error"); }); return d.promise;}, "LastName": Name, "test": Test}}); App.controller (' Myctrl ', function($scope, MyProvider) {alert (myprovider.lastname); alert ( MYPROVIDER.TEST.A) Myprovider.getdata (). Then (function(data) { //alert (data)},function( Data) { //alert (data)}); }); </script></body>            
4. Inject a custom service into the filter
<Body><Divng-app="MYAPP" > Use of services in filters:<H1>{{255 |MyFormat}}</H1></Div><Script> var app = Angular.module (' MyApp ', []); App.service (' Hexafy ',function() { This.myfunc = function (x) { return x.tostring (+)}); App.filter (' MyForm At ', [' Hexafy ', function(hexafy) { return function(x) { return hexafy.myfunc (x);};}]) ; </script></body>            

Delve into angularjs--Custom service details (factory, service, provider)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.