Angular Singletons And Factories
A small proof to myself of how angular factories work. Depending on your style, you could call new in the controller or call new in the factory, then create another singleton that creates the object as shown here... https://docs.angularjs.org/guide/providers
by jrab227
HTML
<div ng-app="application">
<h2>Non-Singleton Version</h2>
<div ng-controller="myCtr1">
<p>Group1:</p>
<button ng-click="click1()">Oneclick {{hold1.count}}</button>
<button ng-click="click2()">Twoclick {{hold2.count}}</button>
</div>
<div ng-controller="myCtr2">
<p>Group2:</p>
<button ng-click="click1()">Oneclick {{hold1.count}}</button>
<button ng-click="click2()">Twoclick {{hold2.count}}</button>
</div>
<h2>Singleton Version</h2>
<div ng-controller="myCtr3">
<p>Group1:</p>
<button ng-click="click1()">Oneclick {{hold1.count}}</button>
<button ng-click="click2()">Twoclick {{hold2.count}}</button>
</div>
<div ng-controller="myCtr4">
<p>Group2:</p>
<button ng-click="click1()">Oneclick {{hold1.count}}</button>
<button ng-click="click2()">Twoclick {{hold2.count}}</button>
</div>
</div>
JavaScript
angular.module('application', [])
.controller('myCtr1', ['tester', '$scope', function(tester, $scope){
$scope.hold1 = new tester;
$scope.hold2 = new tester;
$scope.click1 = function() {
$scope.hold1.add();
};
$scope.click2 = function() {
$scope.hold2.add();
};
}])
.controller('myCtr2', ['tester', '$scope', function(tester, $scope){
$scope.hold1 = new tester;
$scope.hold2 = new tester;
$scope.click1 = function() {
$scope.hold1.add();
};
$scope.click2 = function() {
$scope.hold2.add();
};
}])
.controller('myCtr3', ['testerSingleton', '$scope', function(tester, $scope){
$scope.hold1 = tester;
$scope.hold2 = tester;
$scope.click1 = function() {
$scope.hold1.add();
};
$scope.click2 = function() {
$scope.hold2.add();
};
}])
.controller('myCtr4', ['testerSingleton', '$scope', function(tester, $scope){
$scope.hold1 = tester;
$scope.hold2 = tester;
$scope.click1 = function() {
$scope.hold1.add();
};
$scope.click2 = function() {
$scope.hold2.add();
};
}])
.factory('tester', [function(){
//this one is the constructor method so calling new will create
//non-singletons
return function () {
this.count = 0;
this.add = function(){
this.count++
return this.count;
}
}
}])
.factory('testerSingleton', [function(){
//this one is the object method so this is a full singleton
return {
count :0,
add : function(){
this.count++
return this.count;
}
}
}]);