blog

Home / DeveloperSection / Blogs / AngularJs Services

AngularJs Services

Anonymous User4403 25-Mar-2015

Hi everyone in this blog I’m explaining about AngularJs Services.

Introduction:

AngularJS supports the concepts of "Separation of Concerns" using services architecture. Services are JavaScript functions and are responsible to do a specific task only. This makes them an individual entity which is maintainable and testable. Controllers, filters can call them as on requirement basis. Services are normally injected using dependency injection mechanism of AngularJS.

AngularJS provides many in build services for example, $http, $route, $window, $location etc. Each service is responsible for a specific task for example, $http is used to make Ajax call to get the server data. $route is used to define the routing information and so on. Inbuilt services are always prefixed with $ symbol.

There are two to create a service.

  • v  Factory
  • v  Service
Using Factory Method:

Using factory method, we first define a factory and then assign method to it.

var mainApp = angular.module("mainApp", []);
    mainApp.factory('MathService', function () {
        var factory = {};
        factory.multiply = function (a, b) {
            return a * b
        }
        return factory;
    });
Using Service Method:

Using service method we define a service and then assign method to it. We have also injected an already available service to it.

mainApp.service('CalcService', function (MathService) {
        this.square = function (a) {
            return MathService.multiply(a, a);
        }
    });
Example:

Following example will showcase all the above mentioned directives.

<html>
<head>
    <title>Angular JS Services</title>
    <scriptsrc="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>
    <h2>AngularJS Sample Application</h2>
    <divng-app="mainApp"ng-controller="CalcController">
        <p>
            Enter a number:
            <inputtype="number"ng-model="number"/>
            <buttonng-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>

 

Output:

AngularJs Services


I am a content writter !

Leave Comment

Comments

Liked By