Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs inject module after app initialization

Hello everyone I've been trying to do this with no luck for a few days.

is there anyway to load asynchronously some js scripts(which contain angular modules) and inject them to the running app after it has been initialized.

Basically I have a container DOM element that will be populated with some HTML requested from the server, based on this HTML code I will decide which js files (modules) will be required, then load them asynchronously inject the modules to the angular app and compile the content with the new injected modules.

I tried but every time I do the bootstrap method injecting the module the Main Controller fires up and erases all my scope state. :(

Any help around here?

like image 486
MForce22 Avatar asked Jun 07 '12 01:06

MForce22


People also ask

How do I inject a module in AngularJS?

Injecting a value into an AngularJS controller function is done simply by adding a parameter with the same name as the value (the first parameter passed to the value() function when the value is defined). Here is an example: var myModule = angular. module("myModule", []); myModule.

How modules are loaded in Angular?

To load a feature module eagerly, you need to import that module in application module (AppModule) using imports metadata of @NgModule decorator. When a module is loaded eagerly, it loads all the imported modules, components, services, pipes along with it.

Which components Cannot be injected as a dependency in AngularJS?

Note that you cannot inject "providers" into run blocks. The config method accepts a function, which can be injected with "providers" and "constants" as dependencies. Note that you cannot inject "services" or "values" into configuration.


2 Answers

Perhaps this can help?

app.requires.push("myModule");

injecting module when you have access only to a module variable

like image 62
Rasmus-E Avatar answered Oct 17 '22 13:10

Rasmus-E


It's ugly, but it works: http://jsfiddle.net/MzseV/7/

It basically works by iterating the module's _invokeQueue member and applying functions within using the providers used for registering services, controllers and directives (NOTE: these need to be captured before bootstrapping AFAIK). This will probably also re-register anything you've previously registered so you might want some heuristic to only pick the ones you want, although I'm not sure if there's any damage in re-registring.

Again, it's fairly hideous and hacky so I'd only use as a last resort.

Here's the question I asked and later answered about this.

EDIT: just noticed how old this question is, hope it still helps someone.

like image 3
Jussi Kosunen Avatar answered Oct 17 '22 14:10

Jussi Kosunen