This article mainly introduces the use of factory and service in Angularjs, mainly for customizing the creation of factories and services, the need for friends can refer to the
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 FA Ctory; }); |
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
<html> <head> <title>Angular JS Forms</title> </head> <body> <h2>AngularJS Sample Application</h2> <div ng-app="mainApp" ng-controller="CalcController"> <p>Enter a number: <input type="number" ng-model="number" /> <button ng-click="square()">X<sup>2</sup></button> <p>Result: {{result}}</p> </div> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script> <script> var mainApp = angular.module("mainApp", []); 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> </body> </html>