Kohjah Breese
Kohjah Breese

Reputation: 4136

Dynamically Add Dependencies in AngularJS

I have a JS file with Angular controllers etc. that are used on lots, or many pages. It starts with the line:

var fb = angular.module( 'fb', ['fb.controllers','fb.directives','fb.services','ui.bootstrap'] );

The JS file also contains Angular controllers etc. that are used rarely, that depend on 'ui.bootstrap'.

What solutions are available to move my Angular code to separate JS files and only including the dependency 'ui.bootstrap' when I need it?

Upvotes: 0

Views: 403

Answers (1)

ne4istb
ne4istb

Reputation: 672

You are right, it is strongly recommended to separate such things and also to create one file per controller/directive/filter/etc.

Once you registered module you can use it in the other js files. Angular automatically resolve dependencies.

For example, in fb-controllers.js you register 'fb.controllers' module which depends on 'ui.bootstrap':

angular.module('fb.controllers', ['angular.ui']);

in fb-directives.js you register 'fb.directives' module which ot depends on 'ui.bootstrap':

angular.module('fb.directives', []);

then in app.js you register your main module with dependencies on other:

var fb = angular.module( 'fb', ['fb.controllers','fb.directives']);

Upvotes: 1

Related Questions