StackOverflow_22908508: angularjs-circular-dependency

Illustration of answer to http://stackoverflow.com/questions/22908508/angularjs-circular-dependency.

by wtkd

HTML

<script src="http://code.angularjs.org/1.2.15/angular.min.js"></script>
Open the console to see some action.

JavaScript

var app = angular.module('myApp', []);

/* `service1`: explicit dependency on `service2` */
app.factory('service1', function (service2) {
    return {
        /* Just saying 'Hi' */
        sayHi: function () {
            console.log('Hi from service1');
        },
        /* Calling `service2` to serve you */
        serve: function () {
            console.log('service1 calling service2');
            service2.serve();
        }
    };
});

/* `service2`: Can't have explicit dependency to avoid 
 *             circular dependency issue. 
 *             Injects `service1` at "runtime" instead. */
app.factory('service2', function ($injector) {
    var service1;
    return {
        /* Call a method of `service1` to serve you */
        serve: function () {
            console.log('service2 serving you');

            /* If not already initialized, inject `service1` first */
            if (!service1) { service1 = $injector.get('service1'); }
            service1.sayHi();
            
            /* If you mess things up, e.g. call `service1.serve()`
             * you will create an infinite loop and crash your app */
            //service1.serve();
        }
    };
});

app.run(function (service1, service2) {
    service1.serve();    
});