Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically load modules angular

I'm looking for a way to load a module (js, css and html) with just one directive anytime during the app life.

<my-module id="contacts"></my-module>

And the template of this directive generates

<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>

And the .js file creates a new angular module

// modules/contacts/contacts.js

angular.module('my-contacts', [])
.controller(ContactsCtrl, function($scope) { ... });

And the '.html' uses a controller in this module

// modules/contacts/contacts.html

<ul ng-controller="ContactsCtrl">
  <li ng-repeat="contact in contacts">{{ contact.name }}</li>
</ul>

It wont work because the page's module <html ng-app="my-app"> does not depends on my-contacts module. So I would like every module to inject itself as a my-app dependency.

I've found every module (object returned by angular.module) contains a requires array with it's dependencies. I've injected my-contacts into that array and this works:

// modules/contacts/contacts.js

angular.module('my-app').requires.push('my-contacts');
angular.module('my-contacts', [])
.controller(ContactsCtrl, function($scope) { ... });

But I can't find this property on the documentation. Is it standard or it can change anytime? anyone knows?

Update

To be clear, this is not to load a single module with a single component, this is meant to load a entire application, imagine it like a launcher (like MacOS dockbar or Ubuntu's unity sidebar) with dynamically added icons and when one of this icons are clicked it should run the module. But I don't know at the webpage start which apps this launcher should be able to launch and I need to add more applications dynamically. As each app can has it's own directives and services 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>
like image 351
A. Matías Quezada Avatar asked Nov 12 '22 17:11

A. Matías Quezada


1 Answers

I'm not sure you're trying to abstract the code so much.

What you should be able to do:

  1. Make a module
  2. Put a directive in the module with your contacts list
  3. Inject the module into your page. And use the contact list.
like image 57
bLort Avatar answered Nov 15 '22 02:11

bLort