Introduction to AngularJS using factory and service methods, angularjsfactory

Source: Internet
Author: User

Introduction to AngularJS using factory and service methods, angularjsfactory

AngularJS supports the concept of "separation of concerns" using the service architecture. A service is a JavaScript function and is responsible for only one specific task. This also makes them independent entities for maintenance and testing. Controllers, filters can call them as the basis of requirements. The Service uses AngularJS's dependency injection mechanism to inject normally.

AngularJS provides many internal services, such as $ http, $ route, $ window, and $ location. Each service is responsible for a specific task, for example, $ http is used to create AJAX calls to obtain server data. $ Route is used to define routing information. The built-in service is always prefixed with the $ symbol.

There are two ways to create a service.

  1. Factory
  2. Service

Factory method

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

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

How to use the service

Using the service method, we define a service and then assign the method. It also injects available services.

mainApp.service('CalcService', function(MathService){  this.square = function(a) {  return MathService.multiply(a,a);  }});

Example

The following example shows all the preceding commands.
TestAngularJS.html

Result

Open textangularjs.html in the webbrowser. The result is as follows.

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.