Angular: The issue with lazy-loading a decorator and how to solve it

How to Register a Decorator Synchronously

angular
  .module('myApp')
  .decorator('$controller', MyDecorator);

angular
  .module('myApp')
  .controller('MyCtrl', MyCtrl);

Registering a Decorator Asynchronously

$timeout(function () {
  angular
    .module('myApp')
    .register
    .decorator('$controller', MyDecorator);

  // Make sure controller is registered after decorator
  $timeout(function () {
    angular
      .module('myApp')
      .register
      .controller('MyCtrl', MyCtrl);
  }, 1000);
}, 1000);

What's the issue with the second example?

Answer №1

AngularJS goes through 2 specific phases during bootstrap:

  1. configuration phase
  2. run phase

According to the official documentation:

A module consists of configuration and run blocks that are applied during the application's bootstrapping process. The simplest form of a module contains two types of blocks:

  1. Configuration blocks - executed during provider registrations and configuration phase. Only providers and constants can be injected into configuration blocks to avoid premature service instantiation.
  2. Run blocks - run after the injector is created to start the application. Only instances and constants can be injected into run blocks to prevent system reconfiguration during runtime.

The highlighted sentence in the quote above discusses the importance of run blocks:

This is to prevent further system configuration during application run time.

In the AngularJS decorator documentation:

Similar to $provide.decorator, the module.decorator function executes during the app's config phase. This allows you to define a module.decorator before the decorated service itself.

Hence, decorating a controller (or service or filter) occurs in the configuration phase rather than the run phase.

This clarifies why the "asynchronously registering a decorator" example would not work: attempting to define and decorate the controller within the initCtrl function happens in the run phase, which comes too late for declaring new decorators at this point.

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

A visually stunning image showcase with dynamic resizing and strategically placed white spaces using the m

I'm attempting to create a responsive image gallery using the Masonry jQuery plugin, but despite reading numerous articles and forum posts on the topic, I can't seem to get it to work properly. The gallery is displaying many blank spaces. My app ...

What's the issue with the submit button not functioning on the form?

After downloading a sample form, I encountered the following code: <form id="login-user" method="post" accept-charset="utf-8" action="/home.html" class="simform"> <div class="sminputs"> <div class="input full"> <l ...

Using jQuery to crop an SVG view box

I'm currently working on a sticker website project for a client who requires the ability to crop an image within a specific SVG shape, resembling a Halloween face (shown below). The uploaded image should be displayed only within this shape while hidi ...

Accessing feedback from Reddit's API

After writing some code to search Reddit's API with a specific query, I now want it to display comments as well. Inside my $.getJSON statement that retrieves each title/post based on the search query, I have the following nested code block. The goal i ...

React unit tests experiencing issues with MSW integration

After creating a basic React application, I decided to configure MSW based on the instructions provided in order to set it up for unit tests in both node environment and browser. The main component of the app utilizes a custom hook called useFormSubmission ...

Can a JavaScript function be sent back via AJAX from PHP?

Can a javascript function be returned via Ajax from php? Typically, I would just return a value and handle it in plain javascript. However, since I am working on an Apache Cordova mobile app, I need to approach things differently. account = localStorage.g ...

Is it necessary to match GET and POST routes only if a static file does not match?

I am encountering an issue with my routes and static definitions in Express. Here is my route setup: app.get('/:a/:b/:c', routes.get); Along with this static definition: app.use('/test', express.static(__dirname + '/test')); ...

The complexity of utilizing the map() function in React causes confusion

While delving into React, I stumbled upon this interesting code snippet: {this.state.sections.map(({title, imageUrl, id, size}) => ( <MenuItem key={id} title={title} imageUrl={imageUrl} size={size}/> ))} I'm intrigued by the use of destruc ...

Can anyone help me troubleshoot this issue with uploading external JS scripts into my HTML code?

I'm currently facing an issue with my HTML document where the external js file is not loading. Here's a snippet of the HTML: <!DOCTYPE html> <html> <head> <title>...</title> <meta name="viewport" conten ...

Changing the background color with a switch function in ReactJS

After clicking a link, a view is rendered based on the "id" from a JSON. To enhance the user experience, I want to add a background color when a particular view renders and also toggle the style. This code snippet illustrates how the crawl is displaye ...

AngularJS: Substates not rendering properly

I'm encountering issues while trying to incorporate nested states in my project. Although the View template and JavaScript calls are being made and loaded, the screen is not changing - in other words, the nested screen is not displaying. http://{dom ...

Deploy Node.js on a Debian server hosted on Google Compute Engine

Currently, I am operating a Debian server on Google Compute Engine using a host called example.com. My goal is to run a node.js app within a specific directory on this server, for instance, example.com/mynodeapp. Fortunately, the necessary components such ...

Having trouble getting JSON data to display in CanvasJS

I am trying to retrieve JSON data using Ajax with this code. It works fine when fetching data from the original source, but it's not working with my own JSON data. What could I be missing? Any help would be greatly appreciated. Thank you. $(document) ...

Unexpected behavior: Angular4/Javascript Date object alters when timezone is specified in Date constructor

In my Angular 4 application, I encountered an issue with a date retrieved from an API call. The date is in the format '1990-03-31T23:00:00-06:00' and when attempting to create a Date object and retrieve the month using getMonth(), it returns the ...

Create an array that can contain a mix of nested arrays and objects

Working on my project using Angular and TypeScript includes defining an array that can contain arrays or objects. public arrangedFooterMenu: IMenuItemType[][] | IMenuItemType[] = []; typesOfData.forEach(type => { let filteredData: IMenuItemType | ...

Is there a way to create a navigation menu that highlights as we scroll down the page?

Check out this example of what I am looking for. https://i.stack.imgur.com/fdzvZ.png If you scroll, you will notice that the left menu highlights. Sub-menus will extend when the corresponding menu is highlighted and collapse when other menus are highlig ...

Dropdown box not displaying any choices

I developed a basic reusable component in the following way: Typescript (TS) import {Component, Input, OnInit} from '@angular/core'; import {FormControl} from '@angular/forms'; @Component({ selector: 'app-select', templa ...

I am experiencing issues with my Vue.js application when trying to send an HTTP POST request

I am encountering an issue in my Vuejs application while trying to send an HTTP POST request to my server. The error message that keeps popping up in the console is: TypeError: _api__WEBPACK_IMPORTED_MODULE_0__.default.post is not a function at Object ...

Using Node.js, iterate over every key-value pair within a Redis hash data structure

I am currently navigating my way through the world of redis and node, attempting to iterate over some test hash keys that I have generated. My goal is to display the results on the screen. The expected output should look like this: { "aaData": [['Tim ...

Is the JavaScript Date object consistently displayed in the America/New_York timezone?

The server sends me a time-stamp in milliseconds (Unix time / time from Epoch) with the constant timezone "America/New_York". On my client side, I want to ensure that the time is displayed according to the America/New_York timezone. I have been using Joda- ...