Angularjs custom service tutorial

AngularJS services:

In AngularJS, a service is a function which is used to perform specific task. AngularJS provides many inbuilt services like $http, $route, $window, $location etc.
Note: Inbuilt services are prefixed with $ symbol.

Ways to create a custom service:

1. factory
2. service


      <title>AngularJS Custom Services Example</title>
      <script src = 
      <h2>AngularJS Custom Services Example</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>
         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);
                            function($scope, CalcService) {
            $scope.square = function() {

Try it:

AngularJS Custom Services Example on

Comments are closed.