Henry Tao
Henry Tao

Reputation: 1104

Angularjs module dependencies loop

I am curious and still can not explain dependency loop (passed) in this case.

angular.module('mainApp', ['addon.dashboard']).factory('Test', function(){
    return {
        hello: 'moto'
    };
});
angular.module('addon.dashboard', ['mainApp']).controller('Demo', function(Test){
    console.log(Test.hello);
});

That is a sample code in my app. The mainApp module require to inject addon.dashboard module. Otherwise, addon.dashboard module require to inject mainApp module. We can see that it may loop here. But it work in my app. The controller Demo actually output moto into console.

How does angular deal with loop injection like that?

Upvotes: 4

Views: 444

Answers (1)

rajasaur
rajasaur

Reputation: 5460

You might want to look into the angular code (especially the loadModules method). Basically there is a HashMap that contains all the modules loaded. If its not in the HashMap, it puts it into that and then goes ahead with initializing the rest of the module. IF its already in the set, it will return immediately.

So, in your case, lets say mainApp gets loaded first. It puts it into loadedModules and the goes to find its dependencies. When it finds addon.dashboard, it finds that mainApp is a dependency, but its already present in loadedModules, so it returns immediately.

Its a lot better if you breakpoint into the "loadModules" method of angular.js

Upvotes: 6

Related Questions