Factory vs Service

angularjs factory vs service do the same thing, just a different way of instantiation

by Himanshu Joshi

HTML

<script src="&lt;link href=&quot;http://twitter.github.com/bootstrap/assets/css/bootstrap.css&quot; rel=&quot;stylesheet&quot;&gt;"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-controller="ServiceCtrl">
    <!-- this is never updated after count is changed! -->
    <p> This is my countService variable : {{countService}} {{countService.obj.count}} {{obj.count}}</p>
    
    <p> This is my updated after click variable : {{countS}}</p>
    
    <button ng-click="clickS()" >Service ++ </button>
</div>
<br />
<div ng-controller="FactoryCtrl">
    
    <!--  this is never updated after count is changed! -->
    <p> This is my countFactory variable : {{countFactory}}</p>
    
    <p> This is my updated after click variable : {{countF}}</p>
    
    <button ng-click="clickF()" >Factory ++ </button>
</div>

JavaScript

//angular.js example for factory vs service
var app = angular.module('myApp', []);
    
app.factory('testFactory', function(){
    var countF = 1;
    return {
        getCountF : function () {
            countF++;
            return countF;
        },
        count: countF
    }               
});

app.service('testService', function(){
    var obj = { count: 1};
    this.getCount = function () {
            obj.count++;
            return obj.count;
    };
    this.obj = obj;
    
});

function ServiceCtrl($scope, testService, testFactory)
{
    $scope.countService = testService;
    $scope.obj = $scope.countService.obj;
     $scope.clickS = function () {
        $scope.countS = testService.getCount();
    };

}

function FactoryCtrl($scope, testService, testFactory)
{
    $scope.countFactory = testFactory;
    $scope.clickF = function () {
        $scope.countF = testFactory.getCountF();
    };
}