Issue with Angular: Undefined Controller Error When Implementing Directive

Encountering an issue when trying to incorporate a directive into my website:

Error: [ng:areq] Argument 'MainController' is not a function, got undefined

This problem arises specifically when I include the welcome-directive (welcome.js) in my site. Removing the import allows the controller to function without errors.

Here is the content of my index.html:

<body ng-app="my-app">
  <div ng-controller="MainController">
    <welcome></welcome>
  </div>

  <!-- Angular -->
  <script src="bower_components/angular/angular.js"></script>
  <script src="js/app.js"></script>
  <script src="js/controllers/mainController.js"></script>
  <!-- This line can be removed for the controller to work normally -->
  <script src="js/directives/welcome.js"></script>
</body>

app.js

(function() {
  var app = angular.module('my-app', []);
})();

mainController.js

angular.module('my-app', [])
  .controller('MainController', ['$scope', function($scope) {
    console.log('Controller working');
  }]);

welcome.js

angular.module('my-app', [])
  .directive("welcome", function() {
    return {
      restrict: "E",
      template: "<div>Test test.</div>"
    };
  });

Answer №1

It's important to remember that you are redefining the module, and it should only be defined once.

For example, when you define the module using angular.module('my-app', []), make sure this is done only once. If you need to retrieve it later on, simply use angular.module('my-app').

Here is an example of proper usage:

angular.module('my-app')  //Remember to remove []
  .directive("welcome", function() {
  });

Answer №2

When you pass a second argument in the format of angular.module('my-app', []), it effectively creates a new module which should only be done once.

To access an existing module, you can use

var module = angular.module('my-app')
and then proceed to utilize functions like module.controller(...) or module.directive(....).

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 causing JavaScript to pass the parameter name instead of the element?

Information: I am currently organizing an array of names into two separate arrays - one for names starting with A-M and the other for names starting with N-Z. My goal is to have each entry represented as an object with the name as the property and an empty ...

Formatting numbers in JavaScript objects

I am looking to iterate through an array of objects and convert the string values into numbers. Here is a sample scenario: I have data in a format similar to the variable provided below. When passing this array to a kendo chart, it seems to have trouble r ...

What is the best method for changing a prop in a different component?

I have a list of accounts in my page.js file and I need to access this list in another component that is also rendered within the page.js file: var accounts = []; ... <div className="main"> <LeftPanel accounts={accounts}/> </di ...

Is there a way to change the format of a date and time from YYYY-MM-DD hh mm ss to MonthName, date, year | Hour:Minutes (am/pm) using

How can I convert the date string (2013-03-10 19:43:55) into the format (Mar 10, 2013 | 7:43 pm) using JavaScript or jQuery? ...

Strategies for Repurposing local file.js across multiple Vue projects

I have a file called myfile.js with functions that I want to reuse in multiple vue projects, specifically within the App.vue file. Here is the file structure: -- projec1 ---- src ------ App.vue -- project2 ---- src ------ App.vue -- myfile.js Directly ...

Removing numerous columns from an array on the fly

Currently, I am exploring ways to eliminate multiple columns from an array of objects based on a dynamically selected list of values. If my goal is to delete a specific column, the approach would be as follows: Given the array: arr = [ { "THEDAT ...

How to eliminate quotation marks from an array in JavaScript?

const original_data = ["alpha,beta,gamma","1,2,3","apple,banana,cake"]; updated_data = ["alpha,beta,gamma,1,2,3,apple,banana,cake"] The function is returning the original_data, but I require the updated_data. ...

Using NodeJS, craft a Promise function that implements Sequelize functionality

I'm a newcomer to using Promise and I'm struggling with creating a Promise that incorporates a Sequelize function which already utilizes Promise. I'd like something along the lines of: var geojson = require(path.join(__dirname, 'lib&a ...

The module located at "c:/Users//Desktop/iooioi/src/main/webapp/node_modules/rxjs/Rx" does not have a default export available

I am currently delving into the realm of RxJs. Even after installing rxjs in package.json, why am I still encountering an error that says [ts] Module '"c:/Users//Desktop/iooioi/src/main/webapp/node_modules/rxjs/Rx"' has no default export ...

Navigate to a specific section of the page by scrolling when linked to an id

Just getting started with web development and using Bootstrap to build this site. I'm working on a single-page site where the top navbar directs users to specific IDs. The issue I'm facing is that I want the page to scroll to the ID when clicked ...

Preview not showing CSS changes properly

1) I am encountering an issue with displaying CSS in a form preview tab. Despite setting the CSS, it does not reflect on the fields after clicking the preview button. 2) Are there alternative methods to open the tab in a new window rather than opening it ...

Is there a way to customize the color of an element within CardHeader in MUI?

Is there a way to customize the colors of {note.title} and {note.category}? I have attempted to do so by creating a theme: const theme = createTheme ({ palette: { category: { color: blue } } }) Unfortunately, this appro ...

What is the best way to send ServerSideProps to a different page in Next.js using TypeScript?

import type { NextPage } from 'next' import Head from 'next/head' import Feed from './components/Feed'; import News from './components/News'; import Link from 'next/link'; import axios from 'axios&apo ...

Having trouble choosing an option from the dropdown menu in bootstrap

I'm experiencing an issue with a bootstrap dropdown that I created. I am unable to select an item from it. The code is shown below: var aos = ''; $('.dropdown-item').click(function(event) { event.preventDefault(); // Prevents ...

Node.js Discord Bot: Automatically assigning roles based on user's ID

How can I assign a role to a user using just their user id? It seems like the GuildMember object is needed for this purpose. let member = // retrieve member using id member.roles.add('my role id') ...

What is the best way to include an array in an object while only retaining a single column for each element in the array?

I am working with an array named answers on my webpage, which has the following structure: answers[{x: 1, r: true;},{x: 2,r: false;},{x: 3, r: true;}] I believe I have defined this correctly. The answers array consists of a variable number of rows (in th ...

The error message "TypeError: undefined is not an object (evaluating '_reactNative.Stylesheet.create')" occurred in a React Native environment

I've been working on a project in React Native and have successfully installed all the necessary dependencies. However, upon running the code, I encounter the following error message: TypeError: undefined is not an object (evaluating '_reactNativ ...

What could be causing the issue with the functionality of $templateCache.removeAll()?

Whenever I log out, I make use of $templateCache.removeAll(); to clear the cache. It works perfectly as expected because when I check $templateCache.get("abc.html"), it returns undefined. However, upon reloading the angular app, I noticed that abc.html is ...

Is it necessary to incorporate a Controller along with PostgreSql?

Currently, I'm in the process of working on a project and aiming for well-organized coding practices. However, I find myself puzzled by the concept of controllers. According to my research, it appears that controllers are primarily used when dealing w ...

An application running on Node.js/Express and hosted on Digital Ocean encounters the "Cannot get /" error message

Despite searching extensively online and sifting through numerous solutions to different scenarios, I remained unable to find a fix that resolved my issue. When attempting to run my server.js file locally, everything operates smoothly. However, upon transf ...