Factory vs Service

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

by Nadeesh Peiris

HTML

<script src="https://code.angularjs.org/1.4.7/angular.min.js"></script>
<div ng-controller="HelloCtrl">
    <p>{{fromFactory}}</p>
</div>

JavaScript

var app = angular.module('myApp', ['decoratorModule']);

app.factory('testFactory', function(decoratorService){
 
  World = function(w){
		this.name = w;
  }
  
  World.prototype.change = function(){
  	if(typeof decoratorService.postConstructor === 'function'){
    	this.name = decoratorService.postConstructor(this.name);
    }
  }
  
	sayHello = function(text){
  	var w = new World(text);
    w.change();
		return "Factory says \"Hello " + w.name + "\"";
	}
  
	return {
    sayHello: sayHello
	}               
});

app.controller('HelloCtrl', function($scope, testFactory){
    $scope.fromFactory = testFactory.sayHello("World");   
});

angular.module('decoratorModule', []).factory('decoratorService', function(){  
  return {
	}               
}).decorator('decoratorService', function($delegate){

    $delegate.postConstructor = function(text) {
			return text.toUpperCase();
    }

    return $delegate;
});