Loading Angular Controller in a dynamic fashion

I am attempting to dynamically load controllers using ocLazyLoad:

$ocLazyLoad.load('./ctrls/login.js');

However, I am encountering an error stating:

The controller named 'loginCtrl' is not registered.

angular.module('optimusApp')
    .controller('loginCtrl', function ($scope, $rootScope, $location, $http) {});

app.js

angular.module("optimusApp", ['ngRoute', 'oc.lazyLoad']);
angular.module('optimusApp')
    .controller('globalCtrl', function ($rootScope, $location, $http, $routeParams, $ocLazyLoad) {
        $ocLazyLoad.load('./ctrls/login.js');
    });

Answer №1

I managed to make it function by utilizing ng-if

script.js

var galaxyApp = angular.module("galaxyApp", ["ngRoute", "oc.lazyLoad"])
    .controller("universalCtrl", function ($scope, $location, $http, $routeParams, $ocLazyLoad) {

    $ocLazyLoad.load("./js/app/register.js").then(function() {
         console.log("registerCtrl loaded");
         $rootScope.registerActive = true;
    }, function(e) {
         console.log("error");
    });
});

register.js

galaxyApp.controller('registerCtrl', function ($scope, $rootScope, $location, $http) {

});

HTML

<div ng-if="registerActive" ng-controller="registerCtrl">


</div>

Essentially, you will encounter the "registration error" if your ng-controller is present on the page before the required JS is loaded. Hence, using ng-if proves to be a viable solution, alternatively leveraging ngRoute can also ensure loading of the controller when entering a specific state.

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 could be the reason for the malfunction of .text() and .html() in cheerio js when used with node-fetch?

I am a beginner with Node JS and I am experimenting with the node-fetch and cheerio packages. My goal is to extract data from various websites by testing different URLs and selectors. However, in the code snippet below, regardless of the input selector or ...

Create a random word from a single string within the data in Nuxt.js

I am in need of assistance. In my Vue Nuxtjs project, I am fetching random words generated from my backend Laravel application through an API response. I need to generate multiple random words from a single string value in the data obtained from my Axios r ...

Unable to initiate ng-click event in AngularJS

Looking to trigger a function in TypeScript from the view using AngularJS. My technology stack includes AngularJS, TypeScript, and ASP.Net MVC3. Here is the link in the UI: <div id="left_aside" ng-controller="MyGivingPortfolioController"> <div ...

A guide to toggling the base of a flag in HTML using Angular JS

Two different roles, Client and Manager, need to use the same form. A flag is added in the Controller based on the user role that is logged in. $scope.userFlag=$rootScope.globalSession.UserRole, If logging in as a Manager, $rootScope.globalSession.UserRo ...

Having trouble pushing data to the mongo/express api endpoint

Struggling to insert data into my MongoDB database from my Angular 2 frontend. Despite using morgan to log all requests, nothing seems to be going through as I don't see any entries in the database. Here's my API route: // add venue router.post ...

What is the best method for determining values within JSON data?

In my possession is a JSON file containing user data that looks like this: [ { "id": 0, "username": "Antony", "users": [ { "id& ...

Halt the adhesion of the Bootstrap column when it hits the div section

I have a simple bootstrap row containing two columns: <div class="row"> <div class="col-xs-7"> <p>Walking together</p> </div> <div class="col-xs-5" id="stay"> <p>Joyful journey</p> </div ...

Issue with parsing JSON values in a Chrome extension

Struggling to retrieve the value of a JSON key, but it keeps returning empty. Check out the code snippet below: let json_=JSON.parse(JSON.stringify(result)); console.log(json_); console.log(json ...

The Google Closure Compiler Service is providing faulty code

I've been using Closure Compiler through to minify and obfuscate my JavaScript code, but I seem to be encountering an issue. To troubleshoot, I created a test page with a script. Here's the HTML5 code snippet: <!DOCTYPE html> <html> ...

What is the process for incorporating markers from a JSON file into a PHP webpage using AJAX?

My goal is to display markers on a PHP page using the Google Maps API controlled by radio buttons. All marker data is loading correctly (via JSON), but the map itself is not rendering. I have checked for script exceptions in the console and the run() met ...

Pagination Component for React Material-UI Table

I am interested in learning about Table Pagination in React UI Material. Currently, my goal is to retrieve and display data from an API in a Material UI Table. While I have successfully implemented some data from the API into the Material UI Table, I am ...

What causes objects to be added to an array even when the condition is not met?

In the process of creating a terminal game using node.js, I am developing a random field consisting of different elements such as hats, holes, and pathways. The player's objective is to navigate through the maze and locate their hat within the field. ...

Tips on preventing the mutation of v-model input in Vue

I have a code that calculates the amount of coins from an array. This code helps me determine how many items I can buy from a table with a given order. In the code, orderSize is being mutated in order to get the result. However, when I add an input field f ...

The integration of a side panel with a chrome extension is experiencing issues

I am working on a chrome extension with the following functionalities - Extract URL path from a specific webpage. (The webpage's URL remains constant) Open this URL in a new tab. It can be either http:// or https://. Embed an iframe containing a sim ...

Every time I switch tabs in Material UI, React rebuilds my component

I integrated a Material UI Tabs component into my application, following a similar approach to the one showcased in their Simple Tabs demo. However, I have noticed that the components within each tab — specifically those defined in the render method ...

There was a TypeError encountered while trying to read properties of undefined in Next.js version 13

I've encountered a problem in the title with my post API endpoint that I created in Next.js. The purpose of my endpoint is for form submission, where I gather inputs and send them to my email. Currently, my code successfully sends the email and I rec ...

As you scroll, a box blocks off half of the screen

Hey everyone, I could really use your assistance! I'm working on developing a javascript code and here is the idea - if anyone can contribute to it. It's like a social media platform where users enter the site and the is_user_logged_in parameter ...

Creating custom directives in AngularJS can be a rewarding and powerful

When working with two directives, a situation arose where it was necessary to clear the value in Directive A by using a button located in Directive B. However, when attempting to do this using typical DOM manipulation tools like jQuery, an error occurred w ...

How can I retrieve a text file using an API in a Next.js application?

Is there a way to download a text file using an API in Next.js? The console.log(ninjas) function is already displaying the correct information. I have tested the API with Postman and it works perfectly. When I use GET in Postman, the same information is ...

Troubleshooting Issue with jQuery onclick Function not Transmitting Data

Why is this error occurring: Uncaught TypeError: Object [object global] has no method 'data' HTML: $attributes = array('class' => 'main post', 'onsubmit' => 'validateModules(event)', 'dataid& ...