The Angular controller that has been injected into the app is not defined

In an effort to enhance my simple Angular app, I decided to modularize it. I separated the controller into its own file within a dedicated directory. By employing dependency injection, I ensured the controller's availability in the app module. Combining both files in the HTML was achieved through concatenation/minification. The dependencies for the controller are correctly configured and appear to be functioning as expected.

index.html

<!DOCTYPE html>
<html>
<head>
    <title>Hello Tester Application</title>
    <link rel="stylesheet" href="css/lib/bootstrap.min.css">
    <link rel="stylesheet" href="css/main.min.css">
</head>

<body ng-app="helloTesterApp">

    <header>
        <h1>Hello Tester App</h1>
    </header>

    <p class="description">This application accesses the DropWizard example project to greet users via the API.</p>

    <main ng-controller="HelloController">
        <div class="content-container">
            <input class="input-sm" type="text" name="name" placeholder="Enter your name here" ng-model="user.name">
            <button class="btn" type="button" ng-click="sayHello()">Get Greeting</button>
            <p class="response">Response Message: {{response.message}}</p>
        </div>

        <div>
          <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit sapiente facilis ea harum, nostrum doloribus pariatur totam beatae vero nemo. Assumenda ad qui a rerum reiciendis cumque optio commodi facere.</p>
          <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
        </div>

        <div>
            <p>Current request Port: {{config.port}}</p>
            <p>If you would like to send the request to a different port, enter it here: <input class="input-sm" type="text" name="port" placeholder="alternative port" ng-model="config.altPort"></p>

        </div>
    </main>

    <footer>
      <script src="js/vendor/angular.min.js"></script>
      <script src="js/vendor/angular-route.min.js" charset="utf-8"></script>
      <script src="js/vendor/jquery-2.2.3.min.js" charset="utf-8"></script>
      <script src="js/app.min.js"></script>
    </footer>
</body>
</html>

helloController.js

angular.module('helloController', ['helloService'])
    .controller("HelloController", ['HelloService', '$scope', function($scope, HelloService) {
    $scope.user = {
        name: ""
    };

    $scope.response = {
      message: ""
    };

    $scope.config = {
      port: 9000,
      altPort: 0
    };

    $scope.sayHello = function() {
        $scope.response.message = HelloService.sayHello($scope.user.name, $scope.config.port);
    };
}]);

app.js (v.1)

angular.module('helloTesterApp', ['helloController']);

app.js (v.2)

angular.module('helloTesterApp', ['helloController'])
    .controller('HelloController', HelloController);

I attempted version 2 under the impression that explicitly setting the controller on the application might resolve any issues, yet this led to the error: "Uncaught TypeError: HelloController is not defined." Can someone clarify where I may have gone wrong with this setup? Thank you

Answer №1

It is important for the order of the dependencies to match as you declare and take them as arguments:

Please consider changing:

['HelloService', '$scope', function($scope, HelloService)

To

['HelloService', '$scope', function(HelloService, $scope)

Answer №2

It's important to pay attention to the order of controller injection. Here is a snippet that may help you resolve the issue:

/**
 * QUICKFIX
 */
angular
  .module('helloTesterApp', ['helloService']) 
  .controller('HelloController', HelloController);

HelloController.$inject = ['HelloService', '$scope'];

function HelloController(HelloService, $scope) {
  ... // insert controller's code here
} 

Alternatively, you can improve upon this solution by...

(function() {
  'use strict';

  /**
   * hello.module.js
   */
  angular
    .module('helloTesterApp', [
      /* Shared modules */
      'app.mySharedModule',

      /* Feature areas*/
      'helloService'
    ]);
})();

and

(function() {
  'use strict';

  /**
   * hello.controller.js
   */
  angular
    .module('helloTesterApp') // <-- DIFF HERE
    .controller('HelloController', HelloController);

  HelloController.$inject = ['HelloService', '$scope'];

  function HelloController(HelloService, $scope) {
    ... // insert controller's code here
  } 
})();

If you need further assistance, you can refer to this style guide. I hope this helps in resolving your problem.

Update: Note that it's recommended not to depend on controllers but rather on another module. This might explain why your module definition is incorrect.

angular.module('helloTesterApp', ['helloController'] /* <- This isn't a module */);

To separate the HelloController from app.js, you can do the following:

(function() {
  'use strict';

  angular
    .module('app', [
      'app.hello'
    ]);
})();

Then define a new module, for example, app.hello, in hello.module.js file.

(function() {
  'use strict'

  angular
    .module('app.hello', []);
})();

Lastly, create your controller in hello.controller.js

(function() {
  'use strict';

  angular
    .module('app.hello')
    .controller('HelloController', HelloController);

  HelloController.$inject = ['HelloService', '$scope'];

  function HelloController(HelloService, $scope) {
    // your code
  }
})();

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

Rendering an array of objects in Three JS

I am encountering an error while trying to render an array of objects in a three.js scene. The error message from three.js reads as follows: three.module.js:8589 Uncaught TypeError: Cannot read property 'center' of undefined at Sphere.copy (thr ...

Is there a way to make Outlook show only the caption of a link instead of the entire URL?

In my PDF file, I have set up a button for sending an email. The email is a request that needs approval or denial. I want the recipient to respond with just 2 clicks: Click on either "Approve" or "Deny" (a new email will pop up) Click on "send" - and it& ...

Class component proceeding without waiting for function completion

My function, getactivity(), pulls and sorts data from an API and returns the sorted data in answer1 format. However, I am facing a problem where whenever I run the function to retrieve the data, it keeps returning nothing. Here is the full code: import Re ...

How to change the background color of a slider using jQuery

As a newcomer to web programming, I am currently working on incorporating a slider into my website using jQuery. My goal is to change the background color of the slider to red when the value is less than 5 and green when it exceeds 5. Can this be achieved ...

React-big-calendar: Customize day view to end at 1 am for multiple days

I'm currently in the process of developing a booking system and utilizing react-big-calendar for this project. Situation: A business operates from 9am to 2am the next day, allowing clients to book appointments between 11pm and 1am. Objective: To sho ...

Executing Actions Prior to Redirecting

I am working on implementing a timer process using a custom JQuery plugin that will redirect to the login page after a specific number of minutes. Additionally, when the timer reaches zero, I need to execute a task, which in this case involves making a cal ...

Using PHP to ascertain the requested dataType or responseType from the client

My ajax request is fairly simple: $.post('server.php',data, function (json) {console.log(json)},'json'); I have configured jQuery to expect json data based on the dataType setting. Question: Is the dataType parameter equivalent to re ...

Looking to extract data from JavaScript using Scrapy 1.4.0?

Apologies for my lack of proficiency in English. As a beginner in scrapy, I am seeking guidance on an issue I encountered while trying to scrape a particular website. Below is the code for my spider: import scrapy from bs4 import BeautifulSoup as bs clas ...

I'm facing a challenge where Multer is preventing me from showing images in my React app

Hi there, I'm currently facing an issue where I am using multer to save files on my server and store their path in mongodb. However, I am struggling to display them on my React application. Any assistance would be greatly appreciated. Thank you in ad ...

conceal menu upon click (gradually disappear)

This is a basic HTML/CSS menu. Currently, it is functioning properly for page redirection (href). However, I would like it to hide after being clicked on. I plan to call a function that will initiate an AJAX request upon clicking. Here is the code on JS ...

Troubleshooting an Issue with MediaStreamRecorder in TypeScript: Dealing with

I've been working on an audio recorder that utilizes the user's PC microphone, and everything seems to be functioning correctly. However, I've encountered an error when attempting to record the audio: audioHandler.ts:45 Uncaught TypeError ...

Is your React conditional rendering malfunctioning due to state issues?

I am attempting to create a component that will only be displayed after clicking on a search button. Below is the current code that I have: Update After making some changes, I am now encountering this error: Error: ERROR in /home/holborn/Documents/Work ...

Using AngularJS to bind the ng-valid attribute to a JavaScript function

Hey there! I am interested in setting the validity of an input field using an expression, but not a regular expression. I would like to do something similar to this: <input ng-model="number" required ng-valid="number / 2 > 14"> Is it achievable? ...

Setting state back to default following the conditional rendering of a React component

Whenever the save button is clicked, I aim to display a snackbar component by updating the showSnackbar state to true. To achieve this in React, it's just a simple conditional check in the main render method. The snackbar I'm using here automatic ...

Develop a search feature that automatically filters out special characters when searching through a

I am currently developing a Vue-Vuetify application with a PHP backend. I have a list of contacts that include first names, last names, and other details that are not relevant at the moment. My main query is how to search through this list while disregardi ...

Creating a button that redirects to an external link in CodeIgniter:

Hello everyone, I'm new here and I could really use some assistance with a problem. I am trying to link the button labeled 'lihat rincian' and each row of tables to redirect to an external link like Here's a snapshot of my datatables ...

Is it possible for the req.url path in expressjs to represent a different URL?

Recently, I discovered some suspicious requests being sent to my node-express server. In response, I created a middleware to record the request URLs. After logging these requests, I noticed that most of them started with '/', but there were also ...

Updating state array within reducer leads to duplicate execution of calculations

const updateCartReducer = (state, action)=>{ console.log('running the updater function') const existingItemIndex = state.items.findIndex( (item) => item.restaurant === action.item.restaurant && ...

Developing a function that takes a parameter which can be used with or without an additional argument when invoked

In my React application, I have a method that accepts a parameter for displaying a modal. const displayModal = (p:Result) => { setConfirm(true); if(p) { //check variable for truthy setSelectedRow(p); } ...

The JavaScript code does not call an external function to retrieve data from the database

I'm currently facing an issue with retrieving the same version data from my MySQL (MariaDB) Server. In order to streamline the process and improve maintenance, I decided to create a single connection Object to manage all database queries. However, I&a ...