Load Angular modules dynamically

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>

Answer №1

I'm not convinced that you're attempting to abstract the code as extensively as needed.

Here's what you should aim to accomplish:

  1. Create a module
  2. Include a directive in the module containing your list of contacts
  3. Inject the module into your page and utilize the contact list

Answer №2

Typically, dependencies serve as the second parameter in a module definition. For example:

angular.module('my-app', ['my-contacts']);

Were you asking about this specific aspect? The correct way to handle dependencies and inject them?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What steps do I need to follow to execute React/Next code that I have downloaded from GitHub?

I recently obtained a zip file from https://github.com/prgrms-web-devcourse/Team_Price_Offer_FE and extracted its contents. When attempting to launch the program in Visual Studio Code, I inputted the command npm start but encountered an issue. Team_Price_ ...

Guide to aligning the orientation of an object with a given normal vector using three.js

Imagine I have a car object where the z-rotation is positioned to face the direction it's moving in. This car is situated on an inclined ground represented by a normalized normal vector (nx, ny, nz). How can I rotate the car's x and y axes so th ...

How can we ensure that Ajax consistently provides useful and positive outcomes?

Here is my PHP code: function MailList() { $this->Form['email'] = $_POST["email"]; $index = $this->mgr->getMailList($_POST["email"]); } // SQL code function getMailList($email) { $mailArray = Array(); $sql ...

Enhancing the capabilities of my search and select filter beyond the boundaries of ng-app in AngularJS

In the controller, I have a directive that lists items using data from an API call. The HTML code for this is: <div ng-app="WWnetworkEvents"> <ul ng-controller ="networkEventsCtrl"> <networkevent-directive></networkevent-directiv ...

Retrieve a comprehensive inventory of all routes within a Vue project and automatically create a sitemap for the website - Vue Project

Imagine I've set up a route like this: import Vue from "vue"; import Router from " vue-router"; import BookRoutes from "./routes/book"; Vue.use(Router) const router = new Router({ routes:[ { path ...

Which one should I prioritize learning first - AngularJS or Laravel?

As a novice web developer, I am embarking on my first journey into the world of frameworks. After much consideration, I have narrowed it down to two options: AngularJS and Laravel. Can you offer any advice on which one would be best for me to start with? ...

Why can't JQuery/javascript's dynamic gallery's images be used as buttons instead of links?

I've been struggling with my online portfolio for several nights as I build my website. Despite exhaustive internet searches, I couldn't quite articulate my problem in words and tried multiple workarounds. To see the issue, please visit the beta ...

Is it possible for data passed through props on Vue.js router-view to be visible in browser developer tools?

I have passed several props to the router-view component in this manner: <router-view :zipchange="zipchange" :accountitems="accountitems" :accountloaded="accountloaded" :profilepic="profilepic" /> Upon inspecting an element in the browser's de ...

What is the best way to align text extracted from an API using JavaScript?

I'm currently exploring content generation through APIs, but I'm facing an issue where the text generated is not aligning properly within the container on the screen. The main problem lies in getting the card to be centered on the screen with al ...

Preventing JQuery from interrupting asynchronous initialization

I am currently developing an AngularJS service for a SignalR hub. Below is the factory code for my service: .factory('gameManager', [function () { $.connection.hub.start(); var manager = $.connection.gameManager; return ...

Narrow down JSON file data by a particular value with the help of AngularJS

Here is the current structure of my JSON file: [ { "name":"Bánh bao nướng phô mai thịt", "image":"banhbaonuongphomaithit", "howtocook":"<h1>abc</h1>", "video":"sY6bswxfVGM", "category": "bakery" }, { "name" ...

Implementing VisualCaptcha with AngularJS and slimPHP in a RESTful manner

I am currently using AngularJS on the frontend and SlimPHP on the backend with REST URLs. In an attempt to integrate VisualCaptcha, I followed the instructions on the PHP side and verified that it works. I have a simple Angular dataService that fetches t ...

Encountering an issue when transferring data between controllers utilizing a demo service

During my journey of learning AngularJS, I decided to create a small app that would allow data to be passed between two controllers using services. Below is the code snippet that showcases how I achieved this: The Controller Code <!DOCTYPE html> &l ...

What strategies can be employed to manage three conflicting versions of a single library within a Vite project?

I am currently facing a unique challenge in my web app development process. Specifically, I am using the Vite framework with the svelte-ts template setup to build an application that integrates different libraries for WebXR based augmented reality. The goa ...

retrieving XML information into a div using Ajax and JavaScript

I am currently working on developing a chat application and facing an issue with fetching all logged in users into a div with the ID "chat_members". Despite confirming that the XML file structure is correct, the JavaScript code alongside AJAX does not seem ...

Gulp does not generate any files

Hey there, I'm brand new to using node.js and coding in general. I recently attempted to convert SCSS to CSS using gulp. My gulpfile.js seems to be correct, but when I try running "gulp styles" in the node.js command prompt, I receive the following ou ...

When dynamically adding input fields in Bootstrap, there is a smaller gap between inline inputs

When adding a new list item dynamically in a modal using jQuery append, the spacing in the first li element seems to have a larger gap between the input fields compared to the rest that are added later. Even after checking the developer tools and confirmin ...

Changing JSON variable letter case to lowercase using C#

Utilizing the JSONPEncoderFactory and JSONPBehavior method has allowed me to incorporate JSONP into WCF seamlessly. Everything is set up correctly and my service successfully returns data without any issues. However, I am faced with the challenge of conve ...

Webpack 4 Failing to Properly Render Select Tag

I am encountering an issue with a basic select element that is not displaying correctly due to Webpack. The screenshot below illustrates the final rendered page source, where the closing tag for the select element has been incorrectly positioned before the ...

Execute the function at intervals of 2 seconds until the variable is altered

Is there a way to make sure that the interval function stops running once theImage length exceeds 0? The Code I'm Using var theImages = $('.awesome-slider .slides img'); function checkImages(){ theImages = $('.awesome-slider .sli ...