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.
- Factory
- 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.