English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
AngularJS supports the concept of separation of concerns using the service architecture. Services are JavaScript functions that are only responsible for executing specific tasks. This makes them a maintainable and testable single entity. Controllers and filters can call them as needed. Services are usually injected using AngularJS's dependency injection mechanism.
AngularJS provides many built-in services. For example, $http, $route, $window, $location, etc. Each service is responsible for a specific task, such as $http for making ajax calls to get server data, $route for defining routing information, etc. Built-in services are always prefixed with the $ symbol.
There are two ways to create a service-
Factory
Service
In this method, we first define a factory, 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;});
In this method, we define a service, then assign methods to it. We also inject services that are already available.
mainApp.service('CalcService', function(MathService) { this.square = function(a) { return MathService.multiply(a, a); }});
The following example demonstrates the use of all the above directives-
<html> <head> <title>Angular JS Services</title>/title> <script src = "https://cdn.staticfile.org/angular.js/1.3.14/angular.min.js"> </script> </head> <body> <h2>AngularJS Service Application Example</h/h2> <div ng-app = "mainApp" ng-controller = "CalcController"> <p>Enter a number: <input type = "number" ng-model = "number" /></p> <button ng-click = "square()">X<sup>2</sup>/button> <p>Result: {{result}}</p>/p> </div> <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>Test and See‹/›
Output Results
Open the file in a web browsertestAngularJS.htmand view the results.