The sequencing of initialization for ES6 imports in relation to angular controllers

Recently, I have been working on transitioning an AngularJS application to ES6. In the past, I have followed a pattern where controller files register themselves with the application so that I don't have to worry about which controllers or services are defined in each file. By using require(), I was able to manage dependencies and initialization in a way that allowed me to focus solely on the controller file.

As I explore migrating to ES6 and utilizing import instead of require(), I am facing challenges with code that relies on order dependency. Below is a rough outline (never executed) of what I am aiming to achieve.

So far, I have discovered that I can export a RegisterIndexController() function from index.js and then call it from app.js. This approach works, but I am interested in exploring if I can reverse the flow of dependency. For instance, passing "app" from app.js to a controller.

app.js

app = angular.module('app', ['ui.router'])
angular.element(document).ready(() => angular.bootstrap(document, ['app']))
import './controllers/index'
app.run(() => {})

index.js

app.controller('IndexController', IndexController)

class IndexController {
    /*@ngInject*/
    constructor() {
        this.count = 10
    }
}

index.html

<div ng-controller="IndexController as vm">
  {{ vm.count }}
</div>

Answer №1

Import declarations in ES6 are placed at the top of the file during execution, which means you cannot depend on a specific order. The main issue here is that you are relying on an implicit dependency (app) that has not been defined anywhere. Importing app explicitly would help ensure proper ordering.

It's important to note that class declarations are not hoisted, so your controller registration is currently out of sequence.

Here is how it should be structured:

app.js
export default angular.module('app', ['ui.router']);
index.js
import app from '../app';

app.controller('IndexController', class IndexController {
    /*@ngInject*/
    constructor() {
        this.count = 10
    }
});
entry.js
import app from './app';
import './controllers/index'

angular.element(document).ready(() => angular.bootstrap(document, ['app']))

app.run(() => {
})

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

The initial value in useEffect is not being updated by useState

I am currently implementing a like feature for my web application. The issue lies in the fact that my setLike function is not updating the state even after using setLike(!like). I verified this by adding console.log() statements before and after the setLik ...

Display the webpage following a successful XMLHttpRequest POST request

I'm struggling with rendering a page following an XMLHttpRequest POST. Here's what I have on the client side: var http = new XMLHttpRequest(); var url = window.location.origin + "/mypath"; http.open("POST", url, true); //Include necessary hea ...

Creating a node.js function that can be used with OracleDB

I'm currently delving into learning nodeJS, but I'm facing a roadblock and can't seem to figure out what's causing the issue. Even the Debugger isn't providing much help. Any assistance or guidance would be greatly appreciated. The ...

Choosing a specific element through its CSS selector in Puppeteer

I'm currently working on selecting an image element using its style selector. Initially, I successfully wrote the code in Python, but I seem to be encountering some difficulties while trying to translate it to JavaScript. Below is my progress so far. ...

Create a WebGL object remotely on the server

Exploring potential project ideas, I was curious to see if it's feasible to produce a WebGL scene or object on the server side and then have it rendered on the client. The motivation behind this is that generating a scene typically involves utilizing ...

PhpStorm alerts users to potential issues with Object methods within Vue components when TypeScript is being utilized

When building Vue components with TypeScript (using the lang="ts" attribute in the script tag), there is a warning in PhpStorm (version 2021.2.2) that flags any methods from the native JavaScript Object as "Unresolved function or method". For exa ...

Bringing the Jquery cursor into focus following the addition of an emoji

Looking to add emojis in a contenteditable div but facing an issue with the cursor placement. Here is a DEMO created on codepen.io. The demo includes a tree emoji example where clicking on the emoji adds it to the #text contenteditable div. However, after ...

When you try to upload an image using php/ajax, it causes the page to refresh

I'm currently experiencing an issue with my script. I am successfully using formData() to upload an image via Ajax, which is being saved to the designated folder. However, I am puzzled as to why my page keeps refreshing after move_uploaded_file() is e ...

What could be the reason that setting document.body.style.backgroundImage does not apply to the body element itself?

Consider an HTML document with the given CSS: body { background: url("http://via.placeholder.com/200x200"); width: 200px; height: 200px; } Why does the following code not display the background image URL when executed: console.log(document.body. ...

Is it possible to dynamically generate variables for React hooks during runtime?

Are there any methods to dynamically create variables for react hooks, allowing the values of these variables to be extracted and sent to an API at runtime instead of having predefined variable names set during design time like I am currently doing? Take ...

I encountered a Content Security Policy error while utilizing Disqus on my Jekyll website

I recently created a website using Jekyll and it is hosted on Github Pages: Check out the site, View the repository Here is a snippet from Jekyll's _config.yml: # Comments disqus_shortname: bad3r You can find the Disqus configuration in the _layo ...

Finding the precise source domain address using javascript

I'm having trouble retrieving the original domain address. I've attempted using document.location and $location, but haven't found a solution. Instead of the actual domain address, it returns the IP address. After trying window.location.anc ...

GraphQL/Relay Schema "Field cannot be queried..."

I'm encountering an issue when trying to query specific fields in graphql/relay. My goal is to retrieve the "courseName" field for Courses from the schema provided below. For instance, if I query the User with: { user(id:1){firstname,lastname}} T ...

In Vue.js, you can utilize one property to access additional properties within the same element

Is it possible to access other properties of the same element using a different property in Vue.js? For example: Rather than writing it like this: <kpi title="some_kpi" v-if="displayed_kpi==='some_kpi'"></kpi> I ...

Tips for finishing a row of images using CSS3

Here is the code snippet that I am currently working with: <div id="images" class="img"/> <img src="spiderman.png" alt=""/> <img src="superman.png" alt="" height="25%" width="25%"/> <img src="batman.png" alt="" /> </div> ...

Requesting data from a REST API using a nested query in a GET

After querying data from my MongoDB database, I am faced with the challenge of sending a GET request from the front end to meet this specific query. In my backend code, I retrieve the data using the following: const products = await Product.find({ &apo ...

How can we utilize the transformRequest feature to convert a string into a functional output while making an $http.get

I am currently facing an issue with my web app when sending an $http.get request. The response is a plain-text string that looks like "Hello!" instead of JSON format. I do not want to make changes to the back-end, so I am exploring options to modify the tr ...

Creating a CSS style that automatically adjusts the font size within a container that spans the full height of the

Issue: I have a container set to 100vh, but as the screen size changes, I want the font size to adjust accordingly and always stay within the container without overflowing. Thoughts: While I understand this can be achieved easily with @media CSS rules, I& ...

Observing modifications in either $pristine or $touched states within the transcluded input

I'm currently in the process of creating a directive for an input element that reacts to changes in the model being modified or interacted with. It seems that the mandatory ngModel reflects modifications in the value and view of the input model, but n ...

When PHP echoes a variable, it may reveal one number, but if that variable is then stored in a cookie and later evaluated, a different number may

I am encountering an issue with a variable within a post array called childnumber. This variable is originally a javascript variable sent to the server via an Ajax post. In the PHP script, I have the following: $newValue = $_POST["childnumber"]+1; After ...