angularjs--Custom Service Description (factory, service, provider)

Source: Internet
Author: User

1. The 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>"Utf-8"><script src="Http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>"myApp"Ng-controller="Myctrl"> <p>{{r}}</p></div><script>//Create a model    varApp = Angular.module ('myApp', []); //Create custom services from Factory modeApp.factory ('MyFactory', function () {varService = {};//define an object 'Service.name ="Zhang San"; varAge//define a variable for privatization//Write getter and setter methods on private propertiesService.setage =function (newage) { age=NewAge; } service.getage=function () {returnAge ; }        returnService//returns the object    }); //Create a controllerApp.controller ('Myctrl', function ($scope, myfactory) {myfactory.setage ( -); $scope. R=Myfactory.getage ();    alert (myfactory.name); });</script></body>

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

<script>varApp = Angular.module ('myApp', []); App.factory ('MyFactory', function ($http, $q) {varService = {}; Service.name="Zhang San"; //Request DataService.getdata =function () {varD =$q. Defer (); $http.Get("URL")//the function that reads the data. . Success (function (response) {d.resolve (response); }). Error (function () {D.reject ("Error");            }); returnd.promise; }               returnService;    }); App.controller ('Myctrl', function ($scope, myfactory) {//alert (myfactory.name);myfactory.getdata (). Then (function (data) {Console.log (data);//right when you go here},function (data) {alert (data)//go here when you're wrong        });; });</script>

2.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.

<div ng-app="myApp"Ng-controller="Myctrl"> varApp = Angular.module ('myApp', []); App.service ('MyService', function ($http, $q) { This. Name ="Service";  This. MyFunc =function (x) {returnX.tostring ( -);//Turn 16 binary        }         This. GetData =function () {varD =$q. Defer (); $http.Get("URSL")//the function that reads the data. . Success (function (response) {d.resolve (response); }). Error (function () {alert (0) D.reject ("Error");            }); returnd.promise;    }    }); App.controller ('Myctrl', function ($scope, myservice) {$scope. R= Myservice.myfunc (255); Myservice.getdata (). Then (function (data) {Console.log (data);//right when you go here},function (data) {alert (data)//go here when you're wrong        }); });</script>

3. Provider

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><div ng-app="myApp"Ng-controller="Myctrl"></div><script>varApp = Angular.module ('myApp', []); //It is important to note that when injecting Provider, the name should be: Providername+providerApp. Config (function (myproviderprovider) {myproviderprovider.setname ("The Sage");    }); App.provider ('MyProvider', function () {varName=""; vartest={"a":1,"b":2}; //Note that the setter method must be (set+ variable first letter capitalization) format         This. SetName =function (newName) {name=NewName} This.$Get=function ($http, $q) {return{getdata:function () {varD =$q. Defer (); $http.Get("URL")//the function that reads the data. . Success (function (response) {d.resolve (response); }). Error (function () {D.reject ("Error");                    }); returnd.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>

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.