JSFiddle - React, Tailwind, and code Playground
HTML
<div ng-app="myApp" >
<div ng-controller="myControllerUsingFactory">
<div>
{{test.var1}}
</div>
</div>
<div ng-controller="myControllerUsingService">
<div>
{{test.var1}}
</div>
<div>
{{test.var2}}
</div>
</div>
</div>
JavaScript
/*
* See http://tylermcginnis.com/angularjs-factory-vs-service-vs-provider/
*/
var app = angular.module("myApp", []);
app.controller("myControllerUsingFactory", function($scope, myFactory) {
$scope.test = {};
$scope.test.var1 = myFactory.giveMessage();
/* uncomment the line below and run this app
* notice that then you are trying to use Factory as we can use Service
* this produces an error. myFactory.test is not a function
* this shows that the Factory object has not been instantiated with
* the 'new' keyword as the Service has been
* the implication is that Factory 'services' need to actually return
* a workable object whereas Service 'services' can just attach
* functions to the Service 'class' itself.
*
* which to use? Factory seems a bit more flexible. But really nothin it it.
*
* both are singletons
*
*/
//$scope.test.var1 = myFactory.test();
});
app.controller("myControllerUsingService", function($scope, myService) {
$scope.test = {};
$scope.test.var1 = myService.giveMessage();
//Service doesn't need to return anything
//myService has been instantiated with 'new'
$scope.test.var2 = myService.publicVar;
});
app.factory("myFactory", function() {
var message = "Hi I am a Factory";
var returnedObject = {};
returnedObject.giveMessage = function() {
return message;
}
//only here to demonstate that myFactory is not instantiated with 'new'
this.test = function() {
return "test";
}
return returnedObject;
});
app.service("myService", function() {
var message = "Hi I am a Service";
this.publicVar = "Public Var";
this.giveMessage = function() {
return message;
}
});