Angular's implementing Controller as an ES6 Class: "The ***Controller argument is invalid; it should be a function but is undefined."

Struggling to create a simple Angular todo application using ES6. Despite the controller being registered correctly, I keep encountering an error related to the title when navigating to the associated state.

*Note: App.js referenced in index is the Babel transpiled Webpack output

index.html

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="node_modules/angular-material/angular-material.css" />
  </head>
  <body ng-app="todoApp">
    <script src="../dist/app.js"></script>
    <div ui-view></div>
  </body>
</html>

app.js

import angular from 'angular';
import uiRouter from 'angular-ui-router';
import ngStorage from 'angular-storage';
import ngMaterial from 'angular-material';
import ngAnimate from 'angular-animate';
import ngAria from 'angular-aria';

import config from './config/config'

(() => {
  const ngModule = angular.module('todoApp', [uiRouter, ngStorage, ngAnimate, ngAria, ngMaterial]);
  config(ngModule);
})();

config.js

import httpAuthInterceptor from './interceptors/httpAuthInterceptor';
import constants from './constants';

import login from '../login/index';
import todos from '../todos/index';
import todo from '../todos/todo/index';
import services from '../services/index';

export default ngModule => {
  httpAuthInterceptor(ngModule);
  services(ngModule);

  ngModule.constant('CONSTANTS', constants);

  ngModule.config(($stateProvider, $urlRouterProvider, $httpProvider) => {
    $urlRouterProvider.otherwise('/login');

    $stateProvider
      .state('login', {
        url: '/login',
        templateUrl: 'app/login/login.html',
        controller: 'loginController as vm'
      })
      .state('todos', {
        url: '/todos',
        templateUrl: 'app/todos/todos.html',
        controller: 'todosController as vm'
      });

    $httpProvider.interceptors.push('httpAuthInterceptor');

    login(ngModule);
    todos(ngModule);
    todo(ngModule);
  });
}

login/index.js

import controller from "./login.controller";
import service from "./login.service";

export default ngModule => {
  controller(ngModule);
  service(ngModule);
};

login/login.controller.js

export default ngModule => {
  let controllerName = 'loginController';

  class loginController {
    constructor(loginService) {
      this.loginService = loginService;
      this.username;
      this.password;
    }
  }

  ngModule.controller(controllerName, loginController);
};

I find it perplexing that the service below loads without any issues:

services/index.js

import session from "./session.service";

export default ngModule => {
  session(ngModule);
};

services/session.service.js

export default ngModule => {
  let providerName = 'sessionService';

  class sessionService {
    constructor(store, CONSTANTS) {
      this.CONSTANTS = CONSTANTS;
      this.store = store;

      this.currentSessionToken;

      this.init();
    }

    init() {
      this.currentSessionToken = this.retrieveSession();
      console.log(this.currentSessionToken)
    }

    storeSession (token) {
      this.store.set(this.CONSTANTS.JWT_TOKEN_KEY, token);
      this.currentSessionToken = token;
    }

    retrieveSession() {
      return this.store.get(this.CONSTANTS.JWT_TOKEN_KEY);
    }

    isAuthenticated() {
      let token = this.retrieveSession();
      if(token) {
        let tokenParams = _parseJwt(token);
        return Math.round(new Date().getTime() / 1000) <= tokenParams.exp;
      } else {
        return false;
      }
    }
  }

  ngModule.service(providerName, sessionService);

  let _parseJwt = function(token) {
    let base64Data = token.split('.')[1];
    let base64 = base64Data.replace('-', '+').replace('_', '/');
    return JSON.parse(this.$window.atob(base64));
  }.bind(sessionService);
}

Answer №1

Reorganize the placement of these three function calls

login(ngModule);
todos(ngModule);
todo(ngModule);

Take them out of the config function; they are not meant to be there.

// in config.js

export default ngModule => {
  httpAuthInterceptor(ngModule);
  services(ngModule);
  login(ngModule);
  todos(ngModule);
  todo(ngModule);

  ngModule.constant('CONSTANTS', constants);

  ngModule.config(($stateProvider, $urlRouterProvider, $httpProvider) => {
    // etc

Answer №2

Consider including your controller.js file within the index.html document.

<script src="../dist/login/login.controller.js"></script>

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

Implementing jQuery form validator post anti-SPAM verification?

I am facing what seems like a straightforward JavaScript issue, but my knowledge in this area is still limited. Following a successful implementation of basic anti-SPAM feature that asks the user to solve a simple math problem, how can I integrate jQuery& ...

Revise my perspective on a modification in the backbone model

I am new to using Backbone and I am currently practicing by creating a blog using a JSON file that contains the necessary data. Everything seems to be working, although I know it might not be the best practice most of the time. However, there is one specif ...

What is the best method to retrieve a secure httponly cookie in a Next.js application?

Our next JS application is making a request to The backend team has configured the response cookie as a secure HttpOnly cookie. const session = await ( await fetch( `https://demo.com/auth/session`, requestOptions )).json(); console.log(&qu ...

Concealing a form after submission using JavaScript

After submitting the form, I am attempting to hide it and display a loading GIF. I've experimented with various methods, including changing ClassName to Id, but haven't had success. This is for a school project, and I've spent a significant ...

What is the method to retrieve the index or row number using the map function in Google Sheets?

Currently, I am attempting to retrieve the row number where the row meets certain criteria. However, I seem to be encountering an issue: Instead of getting the desired result, I am obtaining an array like this: [,,2] Although I have attempted using filter ...

Update the message displayed in the user interface after the view has been fully rendered in an Express application, following the execution of asynchronous

I have created a simple express app that reads files from a directory, renames them, zips the files asynchronously, and then renders another view. The file reading and renaming are done synchronously, while the zipping part is handled asynchronously. My cu ...

Setting up Material UI Icons in your React js project

I've been having trouble installing the Material UI Icons package with these commands: npm install @material-ui/icons npm install @material-ui/icons --force npm i @mui/icons-material @mui/material Error messages keep popping up and I can't see ...

encountering the issue of not being able to assign a parameter of type 'string | undefined' to a parameter of type

Seeking help with the following issue: "Argument of type 'string | undefined' is not assignable to parameter of type" I am unsure how to resolve this error. Here is the section of code where it occurs: export interface IDropDown { l ...

Using jQuery to toggle the visibility of table data cells across various tables on a single webpage

On my webpage, I have multiple tables and I'm trying to add more rows or close table data cells using jQuery. However, I seem to be encountering an issue as it's not working properly. <table class="table" ><tr> < ...

Expand the scope of the javascript in your web application to cater

I am in the process of creating a web application that utilizes its own API to display content, and it is done through JavaScript using AJAX. In the past, when working with server-side processing (PHP), I used gettext for translation. However, I am now ...

Using arrow keys and return to effortlessly navigate through text input fields

Currently, I am working on developing a jQuery-based navigation system for switching between multiple input fields. The first part of the code is functioning correctly, allowing users to navigate downwards using either the down arrow or the return key. H ...

Reactjs - There was an error: $node.attr(...).tooltip is not defined

I am currently troubleshooting the SummerNote mention library and encountering an issue - Uncaught TypeError: $node.attr(...).tooltip is not a function The versions I am using are: - "react-summernote": "^2.0.0", - React version: "react": "^16.8.6", ...

forward to a different link following the backend script execution

I am facing a challenge with the signup.php page which includes a Facebook login button. The structure of the page is as follows: <?php if(!isset($_SESSION['logged_in'])) { echo '<div id="results">'; echo '<!-- ...

Issue: Unable to 'locate' or 'access' ./lib/React folder while utilizing webpack

I've been delving into the world of React for a while now and decided to experiment with integrating it with webpack. Below is my webpack.config.js : var path = require('path'); module.exports = { entry: './app.js', outp ...

Tips for showing data from an hour ago in Angular

Here is the code snippet provided: data = [ { 'name' : 'sample' 'date' : '2020-02-18 13:50:01' }, { 'name' : 'sample' 'date' : '2020-02- ...

Issue with useState in Next.js when fetching data from an API

When attempting to retrieve data from the API, I am receiving a response. However, when trying to set the data to useState using the setAccessData function, the data is not being accessed properly. Despite trying multiple methods, the data continues to sho ...

Next.JS: The Key to Long-Term Data Storage

How can we retrieve and maintain data during app initialization or user login so that it persists throughout the application? Currently, every time a page is refreshed, the context is cleared and attempting to use getServerSideProps results in undefined ...

"Pushing elements into an array does not function properly within a promise

I'm having trouble with my code - the push method isn't working and it's not returning anything. import {nearbyUsers, getLatitude, getLongitude} from './helper' const users = [] nearbyUsers(session, getLatitude(), getLongitude()).t ...

Searching Firestore arrays for objects based on one of two fields

Within my document, I am working with the following array: I have a SizeFilterComponent that emits a BaseFilter object when a size is selected. Multiple sizes can be selected. Here is the method handling this logic: selectionChange($event){ let array ...

Ways to verify if a firebase timestamp surpasses the present date

Would you help me with comparing a timestamp field with the current date using JavaScript? This is what I have tried so far: // Initialize an empty array to store documents let myDocs = []; // Call the getDocs function and handle the response await getDo ...