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

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

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

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

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

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


Search Flipkart Products:

No comments: