AngularJS supports the concept of "separation of concerns" in architecture using services. A service is a JavaScript function and is responsible for doing only one specific task. This also makes them a separate entity that is maintained and tested. Controllers, filters can call them as the basis for requirements. The service uses AngularJS's dependency injection mechanism to inject it normally.
AngularJS provides 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 is used to define routing information, etc. The built-in service is always prefixed with the $ symbol.
There are two ways to create a service.
factory
Serve
Using factory methods
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. Also inject services that are already available.
mainApp.service('CalcService', function(MathService){ this.square = function(a) { return MathService.multiply(a,a); }});example
The following examples will show all 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>result
Open textAngularJS.html in a web browser. The results are as follows.
The above is the basic information for AngularJS services. We will continue to organize relevant information in the future. Thank you for your support for this site!