Factory vs Service

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

by yahyaKACEM

HTML

<script src="http://code.angularjs.org/angular-1.0.0rc9.js"></script>
<div ng-controller="HelloCtrl">
    <p>{{fromService}}</p>
    <p>{{fromFactory}}</p>
</div>
<br />
<div ng-controller="GoodbyeCtrl">
    <p>{{fromService}}</p>
    <p>{{fromFactory}}</p>
</div>

JavaScript

//angular.js example for factory vs service
var app = angular.module('myApp', []);
    
app.factory('testFactory', function(){
    return {
        sayHello: function(text){
            return "Factory says \"Hello " + text + "\"";
        },
        sayGoodbye: function(text){
            return "Factory says \"Goodbye " + text + "\"";
        }  
    }               
});

app.service('testService', function(){
    this.sayHello= function(text){
        return "Service says \"Hello " + text + "\"";
    };        
    this.sayGoodbye = function(text){
        return "Service says \"Goodbye " + text + "\"";
    };   
});

function HelloCtrl($scope, testService, testFactory)
{
    $scope.fromService = testService.sayHello("World");
    $scope.fromFactory = testFactory.sayHello("World");
}

function GoodbyeCtrl($scope, testService, testFactory)
{
    $scope.fromService = testService.sayGoodbye("World");
    $scope.fromFactory = testFactory.sayGoodbye("World");
}