Search code examples
javascriptangularjsdeclarationangularjs-controllerangularjs-module

Inject sub module to main module


I want to inject my sub module to main app, but I have injection error

(Error: [ng:areq] http://errors.angularjs.org/1.3.5/ng/areq?p0=SelectionCtrl&p1=not%20aNaNunction%2C%20got%20undefined

it's my main app

enter image description here

and it's my sub module enter image description here

How can I fix that? Thanks!


Solution

  • You are messing up with module declaration. You declared angular.module('app.newProject') two times.

    While creating it first time you registered SelectionCtrl. After that you created another module with same name angular.module('app.newProject,[]') with dependancy and registered TabController1 controller. When you created second module it overrides first one & now it has only TabController1 thats why angular is throwing error SelectionCtrl is required.

    There are several appraoches resolve this approach.

    Approach 1

    Create a module and store it in some variable and use it whenever you want.

    var controllerApp = angular.module('app.newProject', [])
    .controller('SelectionCtrl',function(){ 
        //code here
    });
    
    controllerApp.controller('TabController1',function(){
     //your code here
    });
    

    Approach 2

    Create a module, and whenever you want to use it, use it without dependency.

    angular.module('app.newProject', [])
    .controller('SelectionCtrl',function(){ 
        //code here
    });
    
    angular.module('app.newProject').controller('TabController1',function(){
     //your code here
    });
    

    Approach 3 (I wouldn't prefer this approach)

    Create a module and append you components in linear manners.

    angular.module('app.newProject', [])
    .controller('SelectionCtrl',function(){ 
        //code here
    })
    .controller('TabController1',function(){
     //your code here
    });
    

    I would prefer you to go for Approach 2 which will provide you to bind components any by referring a module.