Factory vs Service

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

by M. Junaid Salaat

HTML

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

JavaScript

//angular.js example for factory vs service
var app = angular.module('myApp', []);
var app1 = angular.module('myApp1', ['myApp']);
   
app.controller('HelloCtrl', HelloCtrl);
app.controller('GoodbyeCtrl', GoodbyeCtrl);
app1.controller('ctrl2', ctrl2);
app.factory('testFactory', function(){
		var _name = 'hello';
    return {
        getName: function(text){
            return _name;
        },
        setName: function(name){
            _name = name;
        }  
    }               
});

function HelloCtrl($scope, testFactory){
    $scope.name = testFactory.getName();
    testFactory.setName('hello2');
}

function GoodbyeCtrl($scope, testFactory){
    $scope.name = testFactory.getName();
    testFactory.setName('hello3');
}

function ctrl2($scope, testFactory){
    $scope.name = testFactory.getName();
}