Introduction to the methods for using factory and service in AngularJS
This article briefly introduces how to use factory and service in AngularJS. It is mainly used to create custom factories and services. For more information, see
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.
Factory
Service
Factory method
Using the factory method, we first define a factory and then assign the method to it.
?
1 2 3 4 5 6 7 8 |
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.
?
1 2 3 4 5 |
MainApp. service ('calcservice', function (MathService ){ This. square = function (){ Return MathService. multiply (a, ); } }); |
Example
The following example shows all the preceding commands.
TestAngularJS.html
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
<Html> <Head> <Title> Angular JS Forms </title> </Head> <Body> <H2> AngularJS Sample Application <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 (){ Return MathService. multiply (a, ); } }); MainApp. controller ('calccontroller', function ($ scope, CalcService ){ $ Scope. square = function (){ $ Scope. result = CalcService. square ($ scope. number ); } }); </Script> </Body> </Html> |