Angularjs Service detailed explanation and sample code _ANGULARJS

Source: Internet
Author: User

ANGULARJS supports the concept of "separation of concerns" with the architecture of services. The service is a JavaScript function and is responsible for doing only one specific task. This also makes them the individual entities that are maintained and tested. controllers, filters can be invoked as a basis for requirements. The service uses the ANGULARJS dependency injection mechanism to inject normal.

ANGULARJS offers such as many intrinsic services, such as: $http, $route, $window, $location, etc. Each service is responsible for, for example, a specific task, $http is used to create AJAX calls to obtain server data. $route used to define routing information, and so on. The built-in service is always prefixed with the $ symbol.

There are two ways to create a service.

Factory

Service

Using factory methods

Using the factory method, we first define a factory and then assign a method to it.

   var Mainapp = angular.module ("Mainapp", []);
   Mainapp.factory (' MathService ', function () {   
     var factory = {}; 
     Factory.multiply = function (A, b) {return
      A * b 
     } return
     factory;
   

Using service methods

Using the service method, we define a service and then allocate the method. It also injects services that are already available.

Mainapp.service (' Calcservice ', function (mathservice) {
  this.square = function (a) { 
		return Mathservice.multiply (a,a); 
	}
);

Example

The following example shows all of the above instructions.

Testangularjs.html

 

Results

Open textangularjs.html in a Web browser. See the results below.

The above is the basic information on the ANGULARJS services, follow-up to continue to collate relevant information, thank you for your support of this site!

Related Article

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.