An error related to Angular module injection occurs while trying to execute my application

I'm new to Angular and I'm a bit confused by this error message. I'm not sure where I went wrong, but my console is displaying the following error:

angular.js:38 Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.5.8/$injector/modulerr?p0=app&p1=Error%3A%20%…(http%3A%2F%2Flocalhost%3A8080%2Flib%2Fangular%2Fangular.min.js%3A21%3A179)(…)

Here's my html code:

<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
   <link rel="stylesheet" href="css/app.min.css">
   <script src="lib/angular/angular.min.js"></script>
   <script src="lib/angular-route/angular-route.min.js"></script>
   <script src="lib/angular-resource/angular-resource.min.js></script>
   <script src="js/app.js"></script>
   <script src="js/controller.js"></script>
</head>
<body>
    test
</body>
</html>

And here's my app.js code:

(function() {
   'use strict';
    angular.module('app', [
        'ngRoute',
        'ngResource',
        'mainController'
    ])
   .config(['$routeProvider', function() {
       routeProvider.when("/", {templateUrl: 'www/index.html', controller:      'mainController'})
   }])

   .controller('mainController', function($scope){
      alert();
   })
 })();

Can someone help me figure out what's wrong?

Answer №1

Instead of being a separate module, the mainController is actually a controller within your existing app module. Therefore, injecting mainController as a dependency does not belong here. Make sure to remove the mainController injection from your modules dependencies array.

On the other hand, ngRoute and ngResources are modules that your module relies on - for example, $routeProvider comes from ngRoute module. To access $routeProvider, you must inject the ngRoute module as a dependency.

Answer №2

There is no need to include the controller as a dependency in the module definition

Instead of:

angular.module('app', ['ngRoute','ngResource','mainController'])

Use:

angular.module('app', ['ngRoute','ngResource'])

Check out the demo here

Answer №3

To begin with, avoid injecting the controller as a dependency. Keep in mind that you register it after creating the module and adding it to that model. Therefore, injecting it at the time of creating the module would not be logical since it does not exist yet. Does this make sense?

Here are some tips to simplify your life: separate your app configuration from your controller registrations. Create an app.js file, for instance, to organize the code. Note how I divided the steps and implemented a config function that is called in the app.config. This enhances readability considering the complexities of JavaScript.

(function() {
'use strict';

var app = angular.module('app', ['ngResource']);

var config = function(routeProvider){
    routeProvider.when("/", {templateUrl: 'www/index.html', controller: 'mainController'});
};

app.config(['$routerProvider'], config); 
}) 
})();

Next, have a mainController.js file containing the controller code and its registration. This approach will better prepare you for future additions of controllers, services, etc. Additionally, instead of using $scope, utilize 'this' - beginning from version 1.5. The only exception is when you need to use $scope with angular charts. Just a heads up ;)

(function ()
{    
'use strict';

var mainController = function ($scope,)
{
    var vm = this;

    vm.variable = "value";
};

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

By the way, please excuse the odd indentation of the code snippets; the editor on this page seems to be causing some issues for me ;)

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 is the best way to prevent selection based on the ng-model in AngularJS?

Can you help me disable the Proxy input field for selection until an Attestor is selected? Currently, both fields are read-only, but if the attestor is not selected, the user should not be able to select the Proxy. I am new to angularJS and would appreciat ...

What could be causing Vite to not locate the '.vue' loader during the Vue 3 migration build process?

Currently in the process of upgrading a Vue 2 project to Vue 3 by utilizing the migration build and vite (https://v3-migration.vuejs.org/breaking-changes/migration-build.html#overview) I've completed steps 1-4 (skipping 4 as I'm not using typesc ...

The FormidableJS form encounters parsing issues when submitted through AngularJS

I have encountered an issue while posting to a formidable form from AngularJS. The form does not parse, and I suspect it might have something to do with the lack of express.bodyParser(). Server-side: ... var form = new formidable.IncomingForm(); console. ...

The change() function isn't being called in the FooterControl of the nested Gridview

In my gridview, there is a nested structure with a footer row for inserting data. When the parent row expands, the footer controls are generated. There are two dropdowns where the second dropdown's options depend on the selection in the first dropdown ...

transmitting a byteArray in a JSON payload using an AngularJS HTTP call

I am trying to send a POST request with a JSON body that includes two attributes. One of them is canvas information generated using fabricjs, and the second one is a byteArray of the project thumbnail. However, I am encountering an issue where I receive nu ...

AngularJS check boxes feature for quizzes

Just starting out with angular and facing what seems like a simple issue. I have a question with multiple answers, one to three of which may be correct. Users can select their answers using checkboxes. The value field indicates whether an answer is true ( ...

Having trouble establishing a connection between Atlas and Node.js

Here is the content of my server.js file: const express = require('express'); const cors = require('cors'); const mongoose = require('mongoose'); require('dotenv').config(); const app = express(); const port = pro ...

The loop outcome is not determined

Storing function arguments in a specific format ["2015-07-05 00:30", 59] ... ["2015-07-05 01:00", 62] function generateCSV(timeAndValue) { object = {} var zero = 0; for(i = 0; i < timeAndValue.length; i++){ var value = timeAndVa ...

Add content to div element using input from textarea

I'm attempting to create a basic text editor where users can input text and by clicking the edit button, it will add that text to the end of the id="textArea". However, nothing happens when I click the edit button after entering text in the textarea. ...

Sequence of background colors not altering as intended

After clicking a button, I included the following jQuery code in a code snippet on my WordPress site: jQuery("#cf_course_planner tr").css("background-color", "#f66"); jQuery("#cf_course_planner tr:eq(0)").css(& ...

Unable to Update the Status Code

When it comes to setting the status code to 9999, I am utilizing the basic Response.StatusCode. In this case, the page is accessed via an AJAX call and the status code is checked at readyState = 4. On detecting 9999 as the status code, an alert pops up wit ...

Tips for accessing elements other than the root element using this.$el

Within my template, the structure is as follows: <div v-show="showContent" class="content-block-body"> <div class="slider-pro"> <div class="sp-slides"> <slide v-for="block in subItems" ...

Can we use ToggleClass to animate elements using jQuery?

I have a section on my website where I want to implement an expand feature. I am currently using jQuery's toggleClass function to achieve this effect. jQuery('.menux').click(function() { jQuery(this).toggleClass('is-active&a ...

What is the best way to clear an XML or table?

As I delve into learning Javascript, I've been experimenting with different approaches to achieve a specific functionality. I'm trying to implement a button that can toggle or hide XML data in a table. My attempts so far have involved adding anot ...

Encountering issues while attempting to transmit several files to backend in React/NestJS resulting in a BAD REQUEST error

My goal is to allow users to upload both their CV and image at the same time as a feature. However, every time I attempt to send both files simultaneously to the backend, I encounter a Bad Request error 400. I have made various attempts to troubleshoot th ...

User retrieval failed following successful passport authentication

After a successful authentication, the user is directed to the "/profile" route, as demonstrated in the code snippet below. app.get( "/auth/google/callback", passport.authenticate("google", { successRedirect: "/profile", failureRedirect: " ...

Custom time selector does not automatically set the default value

After creating two inputs where one represents hours and the other minutes, clicking on edit should display the total time in seconds. The original time for editing should remain unchanged until you choose to save it. Here is the link to the code: https:// ...

Is it possible to verify credit card numbers that contain white spaces using Jquery?

Can someone explain to me how we can validate a credit card number? We currently have a script that accepts numbers like this 4444111122223333 However, I want the credit card validation to allow for credit card numbers in this format (with white spaces. ...

How can I simultaneously add two elements to a single node or to a node that does not exist in the JSON file?

I thought this would be simple, but I'm struggling to find the answer... var crit = { 'webshopId': webshopId, 'type': 'product'} }; I need to include sku.regularPrice = { $gte : parameters.minPr ...

Error: Papa is not defined. The file was loaded from the CDN in the header section

I have integrated the cdn hosted lib for PapaParse in my HTML header. However, when I execute my JavaScript file and it reaches the function where I call Papa.unparse(data); It throws an error stating that Papa is undefined. This has left me puzzled as I h ...