Angular Counter Service

Angular counter service that allows for instantiation.

by jeffaudio

HTML

<h1>Count: {{counter.count}}</h1>
<button ng-click="counter.increment(1)">Add 1</button>
<button ng-click="counter.increment(5)">Add 5</button>
<button ng-click="counter.increment(10)">Add 10</button>

<h1>Count: {{counterB.count}}</h1>
<button ng-click="counterB.increment(1)">Add 1</button>
<button ng-click="counterB.increment(5)">Add 5</button>
<button ng-click="counterB.increment(10)">Add 10</button>

JavaScript

angular.module("fiddle", ["counter"])
.controller("MainCtrl", function($scope, counter) {
    $scope.counter = counter.getInstance();
    $scope.counterB = counter.getInstance();
});

angular.module("counter", [])
.service("counter", function() {
    var counter = function() {
        this.count = 0;
        this.increment = function(x) {
            this.count += x;
        };
    };
    return {
        getInstance: function() { return new counter(); }
    };
});