In AngularJS, services are singletons objects that are instantiated only once per app. Services are used to organize and share code across your app.
It means, services can play major role to perform only specific tasks. Using $scope you can create model data and bind to the views, it does not responsible to manipulate data. Service object contains few useful functions that you can call from Controllers, Directive and Filters etc.
AngularJS comes with several built-in services such as $https, $route, $window, $location etc. AngularJS also allows you to create your own service by registering the service. Once a service is registered, the AngularJS compiler can reference it and load it as a dependency for runtime use.
AngularJS provide two ways to create a service:
Syntax1: Service
var module = angular.module('myapp', []); module.service('customerService', function(){ this.customers = ['Jimi', 'Tom', 'Jake']; });
Syntax2: Factory
var module = angular.module('myapp', []); module.factory('customerService', function(){ var cust = {}; cust.customers = ['Jimi', 'Tom', 'Jake']; return cust; });
<html> <head> <title>My first AngularJS Service code</title> <Script SRC="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.js"> </Script> <Script> //Defining Services Using Service var app = angular.module('app', []); app.service('MathService', function() { this.add = function(a, b) { return a + b }; this.subtract = function(a, b) { return a - b }; this.multiply = function(a, b) { return a * b }; this.divide = function(a, b) { return a / b }; }); app.service('CalculatorService', function(MathService){ this.square = function(a) { return MathService.multiply(a,a); }; this.cube = function(a) { return MathService.multiply(a, MathService.multiply(a,a)); }; }); app.controller('CalculatorController', function($scope, CalculatorService) { $scope.doSquare = function() { $scope.answer = CalculatorService.square($scope.number); } $scope.doCube = function() { $scope.answer = CalculatorService.cube($scope.number); } }); </Script> </head> <body> <div ng-app="app"> <div ng-controller="CalculatorController"> Enter a number: <input ng-model="number" type="number"> <button ng-click="doSquare()">X<sup>2</sup></button> <button ng-click="doCube()">X<sup>3</sup></button> <div>Answer: {{answer}}</div> </div> </div> </div> </body> </html>See Live Example