CodesJava

Easy learning with example program codes

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

Example:

<html>
 
   <head>
      <title>AngularJS Custom Services Example</title>
      <script src = 
      "http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">
     </script>
   </head>
 
   <body>
      <h2>AngularJS Custom Services Example</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>
      </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>

Try it:

AngularJS Custom Services Example on jsbin.com



Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap