AngularJS Lifetime Management

Using $injector for lifetime management

by Jeremy Likness

HTML

<div ng-app='myApp'>
    <div>Count: {{count}}</div>
    <button ng-click="update()">Update</button>
    <div>Counter 2: {{count2}}</div>
    <button ng-click="update2()">Update</button>
</div>

JavaScript

(function (app) {

    function Counter($log) {
        $log.log('Counter created.');
    }

    angular.extend(Counter.prototype, {
        count: 0,
        increment: function () {
            this.count += 1;
            return this.count;
        }
    });

    Counter.$inject = ['$log'];

    app.factory('counterFactory', ['$injector', function (i) {
        return {
            getCounter: function () {
                return i.instantiate(Counter);
            }
        };
    }]);

    app.run(['$rootScope', 'counterFactory', function (rs, cf) {
        var c1 = cf.getCounter(),
            c2 = cf.getCounter();
        rs.count = c1.count;
        rs.update = c1.increment;
        rs.count2 = c2.count;
        rs.update2 = function () {
            rs.count2 = c2.increment();
        };
    }]);
})(angular.module('myApp', []));