Search code examples
angularjsangularjs-scopeangularjs-serviceangularjs-controllerangularjs-module

AngularJs - Injecting child module into other child module


I have a scenario which might sound stupid but I'm stuck and trying to understanding what might be causing it to not work.

I have an angular app which has three modules for now

var app = angular.module('mainApp', ['ngRoute']); //parent module
var reviewModule = angular.module('reviewModule', ['mainApp']);  //child 1
var searchmodule = angular.module('searchmodule', ['mainApp']);  //child 2

I have set some configurations and default strings in my parent module (which is mainApp) which i want to use in all its child modules.

On the other hand, my reviewModule and searchmodule (child modules) have separate controllers and services which I'm using on different routes. Now, the problem comes when i want to use one module's service into the other so for example if i do the following

var searchmodule = angular.module('searchmodule', ['mainApp', 'reviewModule']);

to use reviewModule services in my search module controllers, I get an exception that says

Error: $injector:modulerr Module Error
Failed to instantiate module searchmodule

Both child modules have the same parent and i want to use one child module into the other child module and couldn't understand why I'm getting this exception.

Update:

I even tried using the line below for module declaration

var searchmodule = angular.module('searchmodule', ['reviewModule']);

but this causes an exception too.


Solution

  • This is backwards .... add the secondary modules as dependencies of the main module

    angular.module('reviewModule', []);  
    angular.module('searchmodule', []);  
    
    angular.module('mainApp', ['ngRoute','reviewModule', 'searchmodule']); //parent module
    

    All components of all modules are now available anywhere across the app

    Alternatively you could have one child load another as a dependency but end result is they all need to be bound to the main application module that gets bootstrapped

    Example:

    angular.module('reviewModule', []);  
    angular.module('searchmodule', []);  
    // module just to combine other modules
    angular.module('myChildModules',['reviewModule', 'searchmodule']);
    // add combined modules as dependency of main app module
    angular.module('mainApp', ['ngRoute','myChildModules']);