Is there a way to dynamically load a module (js, css and html) using a single directive at any point during the app's lifecycle?
<my-module id="contacts"></my-module>
The template for this directive looks like this
<my-module id="contacts">
<link type="stylesheet" href="modules/contacts/contacts.css">
<script type="text/javascript" src="modules/contacts/contacts.js"></script>
<ng-include src="modules/contacts/contacts.html"></ng-include>
</my-module>
The '.js' file creates a new angular module
// modules/contacts/contacts.js
angular.module('my-contacts', [])
.controller(ContactsCtrl, function($scope) { ... });
The '.html' file uses a controller from this module
// modules/contacts/contacts.html
<ul ng-controller="ContactsCtrl">
<li ng-repeat="contact in contacts">{{ contact.name }}</li>
</ul>
This currently does not work because the main module of the page, <html ng-app="my-app">
, does not have the dependency on my-contacts
. I want each module to inject itself as a dependency of my-app
.
I noticed that every module created with angular.module
contains a requires
array with its dependencies. By adding my-contacts
into that array, it works:
// modules/contacts/contacts.js
angular.module('my-app').requires.push('my-contacts');
angular.module('my-contacts', [])
.controller(ContactsCtrl, function($scope) { ... });
I couldn't find this property documented anywhere. Is this standard practice or subject to change? Does anyone have insight on this?
Update
To clarify, this isn't just about loading a single module with a component - it's about loading an entire application dynamically, similar to a launcher such as MacOS dockbar or Ubuntu's unity sidebar. The idea is to have dynamically added icons that can launch different modules when clicked, without knowing all the possible apps at the start of the webpage. Each app can have its own directives and services, so I use angular modules as apps.
<body ng-app="my-app">
<ul>
<li ng-repeat="module in modules">
<button ng-click="selectedApp = module.id">{{ module.name }}</button>
</li>
</ul>
<my-module id="{{ selectedApp }}"></my-module>
</body>