Add a new controller to an already running Angular application

Recently, I developed a piece of code that integrates bootstrap modals with Angular, allowing for the loading of links into modals upon click. The challenge arose when these links contained their own Angular controllers embedded within them. While attempting to load the modal, I used jQuery to bring in all necessary scripts before compiling the modal using Angular to make it function correctly. However, an issue emerged where even though I defined the controller dynamically at runtime during the modal load process, Angular failed to recognize it and threw an error (Uncaught Error: Argument 'ControllerName' is not a function, got undefined).

Is there a way to instruct Angular to acknowledge the new controller added during runtime?

Below is a snippet of the prototype modal code that I am currently utilizing:

var directivesModule = angular.module('modal.directives', []);
directivesModule.directive("modal", function(ModalService) {
    return function($scope, elem, attrs) {
            elem.on("click", function(e) {
                e.preventDefault();
                var url = $(this).attr('href');

                ModalService.load(url, $scope);
            });
    };
});

var servicesModule = angular.module('modal.service', []);
servicesModule.factory('ModalService', function ($http, $compile, $rootScope)
{
    var ModalService = {};

    // Code for loading and displaying the modal goes here

    return ModalService;
});

Answer №1

Absolutely, it is indeed achievable, and angular already contains all the necessary tools. While I can't offer you a complete code solution at this moment, here's a snippet to guide you in the right direction:

  1. Begin by loading your HTML content directly into the DOM -- something along the lines of $('#myDiv').load('dialog.html'). Avoid associating controllers with ng-controller! Retain a reference to the DOM element (let's call it element).

  2. Proceed to load your controller -- possibly utilizing head.js or any method that suits your context best. Keep a pointer to the controller function (naming it as controller would make sense). You don't have to formally register it within your angular app; stick with a straightforward global function format. Include any essential services and scope references as needed:

function MyController($scope, $resource, $http, $whatever, YourService) {
    $scope.greetings = 'globe';
}
  1. Connect all the components together:
function ($compile, $rootScope, $inject) {
    var element = angular.element('#myDiv'),
        controller = MyController;

    // A fresh scope is required:
    var $scope = $rootScope.$new(true);

    // Compile the loaded HTML section and connect it with the scope:
    $compile(element)($scope);

    $inject.invoke(controller, {
        $scope:$scope // additional locals can also be included here based on your controller needs
    });
}

Please note that while there's no guarantee that this code will work flawlessly without adjustments, it encapsulates the approach I utilized a few weeks back. However, it's important to mention that this technique won't permit dynamic incorporation of AngularJS dependencies: your application must encompass all potential modules prior to bootstrapping.

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 is the best way to utilize ajax for uploading both a text field and a file simultaneously?

I am currently new to AJAX and working on implementing a form that uploads a name and a file to a PHP file for processing and insertion into a database using mysqli. While the PHP file works, I am facing issues with the AJAX code. I have tried implementati ...

Creating a Circle with Pixi.js v4 and Typerscript in IONIC 2

I have been attempting to create a custom class in TypeScript that utilizes PIXI.js to draw circles. Below is the code for my home.ts class: import { Component, ViewChild, ElementRef } from '@angular/core'; import { NavController } from 'i ...

Combine words into lowercase in JavaScript variable

I'm struggling to understand why the data from a form field input is not being stored correctly in a SharePoint column data collection. Currently, when someone inputs a name into a form field, it should automatically populate a SharePoint list: http ...

Strip all null entries from the URL string

I'm attempting to eliminate all empty parameters from a URL string. This is how my URL appears: http://localhost/wm/frontend/www/?test=&lol=1&boo=2 The desired output from my code should be: http://localhost/wm/frontend/www/?lol=1&boo=2 ...

What is the formula for finding the distance from the top-left corner of an HTML element to the top-left corner of the window?

Looking for a simple way to accomplish this? Take into account properties such as border and padding. Will this approach be effective even with box-sizing set to content-box or border-box? ...

Is there a way to combine several WAV audio blobs into one cohesive file?

Issue I'm Facing: I am attempting to combine multiple blob audio files into a single blob and then download it on the page. My Attempts So Far: I have tried to merge the Audio blobs using the following methods: Method - 1: const url = window.URL.c ...

Circular dependency in typescript caused by decorator circular reference

Dealing with a circular dependency issue in my decorators, where the class ThingA has a relation with ThingB and vice versa is causing problems for me. I've looked into various solutions that others have proposed: Beautiful fix for circular depende ...

Utilizing JavaScript to create multiple HTML tables from JSON data

Is it necessary to create separate tables in HTML for each set of JSON data when all tables have the same number of columns (2 columns)? I am looking to minimize the JavaScript function that displays the table with the current JSON data. Can I use one tabl ...

Error message: Angular JS encountered an issue when trying to initiate the test module. The cause

When I run JavaScript within an HTML file and use AngularJS with ng-repeat function, I encounter this console error: angular.js:38 Uncaught Error: [$injector:modulerr] Clicking on the link in the error message leads to: Failed to instantiate module test ...

I am unable to choose the search items

I am currently working on creating a search functionality using PHP, MySQL, JavaScript, and AJAX. However, I am encountering an issue with selecting the suggested search items. Even though I have implemented the load suggestions feature, I am unable to sel ...

Converting milliseconds to a valid date object using Angular form validation

I am facing an issue with form validation and milliseconds in my Angular application. It seems that Angular does not consider time in milliseconds as a valid date format, causing the angular.isDate(1418645071000) function to return false. How can I modify ...

How can I align two inner boxes vertically in the most efficient manner?

.dd{ height:100px; width:100%; border:1px soild red; background:#000; } .dd .d1{ height:20px; width:20px; border:1px solid green; display:inline-block; } .dd .d2{ height:20px; width:20px; border:1px solid green; display:inl ...

The class styling is malfunctioning

When I click the 'night' button, I want the word color in the class=css to change to white. However, this is not working as intended, even though all other word colors are changing correctly. Here is my code: .css { font-weight: bold; ...

Transferring information from Child to Parent using pure Javascript in VueJS

I am familiar with using $emit to pass data from child components to parent components in VueJS, but I am trying to retrieve that value in a JavaScript function. Here is my situation: Parent Component created () { this.$on('getValue', func ...

Assistance required in designing a unique shape using Three.js

https://i.sstatic.net/pmHP2.png Hello there! I could use some assistance with replicating the 2D shape shown in the image above using three.js. Specifically, I'm encountering some difficulty with incorporating the subtle curvature seen on the inner l ...

When you try to create a popover, a cautionary message pops up indicating that $tooltip is no longer supported. It is

I need help with creating a popover that appears when hovering over an anchor tag. Here is the code I am using: angular: 1.4.2 ui-bootstrap :0.14.2 <div class="row" ng-repeat="endorsement in endorsements| filter: {category:categorySelected}"> &l ...

What is the best way to ensure that the input submit element is only visible after the input checkbox element has been checked?

For a school project, I am attempting to create a simulated reCAPTCHA box. Although my code is complete, I would like the functionality to submit your response from the input fields above only after selecting the reCAPTCHA checkbox. Upon researching, it ap ...

Deactivated a specific radio button with a particular class attribute

Is there a way to disable radio buttons with a specific class using JavaScript? I attempted the following code: if( $("input[type=radio]").hasClass("class-full") ){ $(this).attr('disabled', true); } However, it does not seem to be effective ...

Is it possible to rebind data on a RadCombobox using ajax?

Recently, I've been restructuring my workflow by utilizing a webservice to help me better organize things. This has made using AJAX much simpler and efficient for me. Currently, when a user wants to save a new contact, they are added to a database th ...

AngularJS enables the loading of directives dynamically, but sometimes encounters errors such as "Restricted URI access denied."

Presently, I am in the process of developing a small educational project using HTML5, CSS, JS and AngularJS. Hiccup: Loading an AngularJS Directive in my index.html file Error code [1] - Local browser Error: Access to restricted URI denied Various resp ...