Search code examples
angularjsangularjs-directiveangularjs-module

Can parent module directives be used in child modules like controllers?


Just as controllers are module "level" independent and can be used anywhere in the entire application stack I am wondering if there is a way for child module to use the parent modules directives without having to assign them as dependency for each child module.

Example of how I was hoping to have directives work (in the view of a controller):

angular.module('app.child').config(function($stateProvider) {
  $stateProvider.state('child', {
    url: '/child',
    views: {
      'header': {
        controller: 'parentController',
        templateUrl: 'child.html'
      }
    }
  });
});

angular.module('app').controller('parentController', function () {
  console.log('test');
});

So what I am wondering is if

angular.module('app', ['app.child']);
angular.module('app.child', ['ui.router']);

can also be written as

angular.module('app', ['app.child', 'ui.router']);
angular.module('app.child', []);

in some way where ui.router is still available for the child module.

If I do this in my existing project I get $injector errors.


Solution

  • Just as controllers are module "level" independent and can be used anywhere

    This is true and that is something you should never do. Module should be self-consistent and independent from parent modules - it should declare all required dependencies.

    I.e. if you have 2 modules: app and app.child, and in some place in app.child you have: <div ui-sref=... than your app.child must depend on ui-router. (This will still work if it doesnt, but parent does - but this does not mean that this is correct way)

    N.B. A lot of apps can leave within single module. Are you sure you need more than one?