Home  >  Article  >  Web Front-end  >  Introduction to the methods of using factory and service in AngularJS_AngularJS

Introduction to the methods of using factory and service in AngularJS_AngularJS

WBOY
WBOYOriginal
2016-05-16 15:54:331091browse

AngularJS supports the concept of "separation of concerns" in an architecture using services. Services are JavaScript functions and are responsible for doing only one specific task. This also makes them separate entities for maintenance and testing. Controllers, filters can call them as a basis for requirements. Services are injected normally using AngularJS's dependency injection mechanism.

AngularJS provides many intrinsic services, such as: $http, $route, $window, $location, etc. Each service is responsible for a specific task, for example $http is used to create AJAX calls to get data from the server. $route is used to define routing information, etc. Built-in services are always prefixed with a $ sign.

There are two ways to create a service.

  1. Factory
  2. Service

Use factory method

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

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

Use service method

Using service methods, we define a service and then assign methods. Also inject already available services.

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

Example

The following example will demonstrate all the above commands.
testAngularJS.html



  Angular JS Forms


  

AngularJS Sample Application

Enter a number:

Result: {{result}}

<script> var mainApp = angular.module(&quot;mainApp&quot;, []); mainApp.factory('MathService', function() { var factory = {}; factory.multiply = function(a, b) { return a * b } return factory; }); mainApp.service('CalcService', function(MathService){ this.square = function(a) { return MathService.multiply(a,a); } }); mainApp.controller('CalcController', function($scope, CalcService) { $scope.square = function() { $scope.result = CalcService.square($scope.number); } }); </script>

Results

Open textAngularJS.html in your web browser. See the results below.

2015617105555351.jpg (560×429)

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn