AngularJS (ii)--Custom service with AngularJS

Source: Internet
Author: User

like Java , the controller in the AngularJS should be as concise as possible, not advocating DOM in the controller Operations and data operations. First look at a bloated, hard-to-maintain controller :

var app = angular.module (' Appmodule ',  []); App.controller (' Maincontroller ',  function ($scope)  {   $scope .shouldshowlogin =  true;   $scope. Showlogin = function ()  {     $scope. Shouldshowlogin  =! $scope. Shouldshowlogin;}; $scope. Clickbutton = function ()  {  $ (' #btnspan '). html (' Clicked ');}; $scope. Onlogin = function (user)  {   $http ({    method:  ' POST ' ,    url:  '/login ',    data: {       user: user  }  }). Success (function data)  {    //some  actions  }); 

Coding Beginners always tend to write this code. A more elegant approach is to make the controller lighter and easier to maintain by using service and directive . Here's a look at how to customize and use the service .

1. Create a custom service with factory () :

var app =angular.module (' Appmodule ',  []); App.factory (' UserService ', [   ' $http ',   function ($http)  {    var  Runlogin = function (user)  {       $http ({         method:  ' POST ',     url:  '/login ',      data: {       user: user      }    }). Success (function data)  {      // some actions    });    };        return {      runLogin: runLogin    };   }]); 

It's not hard to see that, after declaring a custom service, we put the login logic in the previous bloated controller into the UserService , and the code immediately becomes full.

2. Use a custom service:

App.controller (' Maincontroller ', [' $scope ', ' UserService ', function ($scope, userservice) {$scope. Onlogin = function (user)    {userservice.runlogin (user);  }; }]);

Here's UserService is our custom service, which is injected at Controller initialization to use the values and methods. Note that injecting all of the AngularJS built-in services before customizing the service is a convention commonly known as the rule.

If the custom service and the controller that is using it are not in a module , the controller must be in the module the module in which the service is injected when initializing :

var servicemodule = angular.module (' Servicemodule ', []) servicemodule.factory (' UserService ', [' $http ', function ($ HTTP) {...//same as Previous userservice}]);//Inject the Modulevar app =angular.module (' Appmodule ') in the module where the controller resides, [' Serv Icemodule ']); App.controller (' Maincontroller ', [' $scope ', ' UserService ', function ($scope, userservice) {...//With previous CONTR Oller (same}]);

3. Other ways to Create a custom service :

The factory () method is the most general way to create a service, but there are other ways to create a service.

3.1 provider () :

App.provider (' UserService ', {self:this, setname:function (name) {self.name = name;      }, $get: function () {return {getname:function () {return self.name;  }    }; }});

When created with provider () , the returned object must have a $get () function object, otherwise the creation fails. Creating a service with provider () allows for greater extensibility when multiple applications use the same service, and is extended as follows:

App. Config (function (userserviceprovider) {nameserviceprovider.setname (' Lucy ');});

among them, Userserviceprovider is composed of the corresponding service name + Provider , which can be called by the method in UserService.

3.2 constant () :

The method can register the variable value as a service, which can be shared by other module or controller :

App.constant (' Astoken ', ' 12345 '); App.controller (' Maincontroller ', [' $scope ', ' astoken ',//inject constant function ($ Scope, Astoken) {//some Actions}]);

After injecting the constant, it can be used directly.

3.3 Value ():

Same as constant () usage. the difference from constant () is thatconstant () can be injected into config , and value () does not:

App.constant (' Astoken ', ' 12345 '). config (function (astoken) {//normal use}), App.constant (' Asvalue ', ' 12345 '). config ( function (asvalue) {//asvalue cannot be accessed in config});

4.AngularJS The Interceptor in the $provide. Decorator () :

angularjs $provide 3.1 created UserService

App. Config ([   ' $provide ',   function ($provide)  {    $ Provide.decorator (' userservice ', [       ' $delegate ',       function ($delegate)  {        return{           getname: function ()  {             return  $delegate. GetName ()  +  '  <--  thefunction has been decorated. '           },           getage: function ()  {             return 18;          }         };      }    ]);  }]); 

as shown above, in config , by $provide. Decorate () method to intercept userservice , injected $delegate You can invoke the method of the original service to intercept . Here we intercept the UserService , modify the GetName () method in the UserService , and add the userservice to the Getage () method.

Finish.

Resources:

the AngularJS Authoritative tutorial "Ari Lerner Translator: Shano Xu Fei He Pengfei


This article is from the "barrel of fake dog excrement" blog, please be sure to keep this source http://xitongjiagoushi.blog.51cto.com/9975742/1659620

AngularJS (ii)--Custom service with AngularJS

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.