Tuesday, June 23, 2015

AngularJS Service vs Factory

Form a normal usage perspective both the Service and Factory provide the same functionality, both Service and Factory are Singleton, however there are few differences between the two, let us see on how they differ.

When we invoke a service it returns an instance (object representation) of the function, which is more like initializing the object with new and returning the instance.

When we invoke a factory it returns a class representation of the function, the calling Function/Controller can initiate the response (new). Following is the Syntax for Service and Factory
Services – Syntax
app.service('serviceName', function)
{
          //Implementation code here
};

Factory – Syntax
app.factory('factoryName', function)
{
          //Implementation code here
};


The following example shows usage of both Service and Factory implementation.

The following example shows how to define and use a factory services in AngularJS

Service.html
<html ng-app="ServiceApp">
<body>
<div ng-controller="ServiceAppController">
<h3>{{title}}</h3>
<b>Hello Service:</b> {{HelloService}}<br/><br/>
<b>Hello Factory:</b> {{HelloFactory}}<br/><br/>
</div>
    <script src="angular.min.js"></script>
    <script src="ServiceApp.js"></script>
    <script src="Service.js"></script>
    <script src="ServiceController.js"></script>
</body>
</html>

ServiceApp.js
var app = angular.module("ServiceApp", []);

Service.js
app.service('HelloService', function () {
          this.SayHello = function(){
                   return "Hello World from Service!!!";
          }
});

app.factory('HelloFactory', function() {
    return {
        SayHello: function() {
            return "Hello World from Factory!!!";
        }
    };
});

ServiceController.js
app.controller("ServiceAppController", function($scope, HelloService, HelloFactory) {
    $scope.title = "Service and Factory in AngularJS";
    $scope.HelloService = HelloService.SayHello();
   $scope.HelloFactory = HelloFactory.SayHello();
});

Output


Search Flipkart Products:
Flipkart.com

No comments: