Services vs. Factories
Example of services vs. factories using Angular service and factory
by Jeremy Likness
HTML
<div ng-app="myApp">
<span ng-repeat="n in counts track by $index">{{n}}
<span ng-if="!$last">,</span>
</span>
</div>
JavaScript
(function () {
var app = angular.module("myApp", []);
function Singleton() {
var count = 0;
this.getCount = function () {
count += 1;
return count;
};
}
function Factory() {
this.getCounter = function () {
return new Singleton();
};
}
app.service("svcSingle", Singleton);
app.service("svcFactory", Factory);
app.factory("facSingle", function () {
return new Singleton();
});
app.factory("facFactory", function () {
return new Factory();
});
app.run(["$rootScope", "svcSingle", "svcFactory", "facSingle", "facFactory",
function($rootScope, ss, sf, fs, ff) {
var counts = [];
counts.push(ss.getCount());
counts.push(ss.getCount());
counts.push(fs.getCount());
counts.push(fs.getCount());
counts.push(sf.getCounter().getCount());
counts.push(sf.getCounter().getCount());
counts.push(ff.getCounter().getCount());
counts.push(ff.getCounter().getCount());
$rootScope.counts = counts;
}]);
})();