I have an application that consists of N Modules. Almost all of those modules will be loaded on demand.
Is there any good way to organize AngularJS application with dynamically loaded and unloaded modules?
The $scope in an AngularJS is a built-in object, which contains application data and methods. You can create properties to a $scope object inside a controller function and assign a value or function to it. The $scope is glue between a controller and view (HTML).
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.
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.
As of Angular 1.2.16 and 1.3.0 beta, the bootstrap()
method defines a specific element on the DOM as the root scope for a collection of modules. There is no corresponding method to unbind. The ng-app
directive is just a shortcut for bootstrap()
, so the same limitation applies.
The angular-requirejs-seed project Artemis linked to does not answer your question. It uses the NG_DEFER_BOOTSTRAP!
property to suspend the bootstrap process and dynamically define which modules to add at the time the page is loaded. It does not unload anything.
The most straightforward way to overcome Angular’s inherent inability to unload modules is to destroy the DOM element where your modules are running. Unfortunately, by destroying the element, you also lose whatever markup you had. One solution to that problem is to put your app’s markup into an HTML5 <template>
element and clone its contents. Here’s an example I wrote in JSBin where an ambiguously named someGuyInASuit
directive loads a picture of Dr. Jekyll or Mr. Hyde depending on which module is loaded.
This work-around is not well suited to an app consisting of many modules, especially if you intend to swap them in and out frequently as the user interacts with it. For one, all your models will be destroyed. Also, all the config()
and run()
blocks will be re-run. You may want to either fork Angular and add your own un-bootstrap method or have a look at another framework such as React, which has a method for unloading components built in.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With