Angular: The specified controller has not been registered

I've been stuck on this problem for a few hours now, and no solution seems to work. I've searched for similar issues but haven't found any fixes that apply to my situation.

The main issue I'm facing is with registering controllers. I can only register controllers within the same file where I declare the app. When trying to set up the 'MainController' in a separate file, I get an error saying "The controller with the name 'MainController' is not registered." Moving MainController to the same file as the app declaration solves the problem, but makes the code difficult to navigate when multiple controllers are involved. Here's an example of my code:

angular.module('myApp', ['ngRoute']);

angular.module('myApp')
  .controller('MainController', MainController);

However, other controllers kept in different files fail to register. For instance, in home.controller.js:

angular.module('myApp')
  .controller('HomeController', HomeController);

function HomeController(HomeService) {

}

This HomeController doesn't register, and I'm unsure why. Each HTML partial in ng-view has its own controller, and ng-view is nested within MainController. Below is the content of app.config.js:

angular.module('myApp')
  .config(function($routeProvider, $locationProvider) {
    $routeProvider.when('/home', {
      templateUrl: 'views/home.html',
      controller: 'HomeController as home'
    }).when('/profile', {
      templateUrl: 'views/profile.html',
      controller: 'ProfileController as profile'
    });

    $locationProvider.html5Mode(true);
  });

Lastly, here's part of index.html:

<!DOCTYPE html>
<html ng-app="myApp">
  <head>
    <meta charset="utf-8">
    <title>My App</title>
    <script src="vendors/angular.min.js"></script>
    <script src="vendors/angular-route.min.js"></script>

    <script src="scripts/app.module.js"></script>
    <script src="scripts/app.config.js"></script>

    <scripts src="scripts/home.controller.js"></scripts>
    <scripts src="scripts/profile.controller.js"></scripts>

    <script src="scripts/main.service.js"></script>
    <script src="scripts/home.service.js"></script>
    <script src="scripts/profile.service.js"></script>

    <base href="/" />
  </head>
  <body ng-controller="MainController as main">
    <header>
      <h1>My App</h1>
    </header>
    <!-- Content varies -->
    <div class="container">
      <ng-view></ng-view>
    </div>
  </body>
</html>

I've successfully handled similar projects in the past without any issues, so I'm at a loss as to what could be causing this particular problem. Any assistance would be greatly appreciated!

Answer №1

Previously, I encountered a similar issue related to the order of script loading, particularly when using async script loading. It seems like you are not doing that in your case.

To troubleshoot this problem:

Insert a console log statement inside the controller's function body (

console.log('registering controller x')
). This statement may either not appear at all, or show up after the error occurs.

In the past, Angular (and most likely still does) waited for the entire app and all controllers to be registered before executing the code. It could be possible that Angular is not waiting for this specific controller, or the controller itself is not running properly.

Next step would be to double-check the file reference correctness (add a console.log at the beginning of the file), or investigate how Angular determines the completion of controller registration process and why it might skip over your controller.

I haven't worked with Angular since version 1.2 as I found it quite problematic. However, my experience then indicates similar architectural issues. Back in the day, Angular relied on Document.ready which caused conflicts with my async script loading. Hopefully, they have improved this aspect by now.

Wishing you the best of luck in resolving this issue.

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 process for accessing the data attributes of div elements and then transferring them to a cookie?

Although this question may have been answered before, I couldn't find a specific solution. Imagine I have the following div elements... <div class="listings-area"> <div itemtype="http://schema.org/Product" itemscope=""> <a class="lis ...

Apply SetTimeout exclusively for desktop devices

A website I'm working on has a background video from YouTube using YTPlayer. To enhance the user experience, I have implemented a CSS spinner that displays while the page is loading. However, I noticed that the spinner disappears before the video fini ...

Analyzing the elements of an array in JavaScript and making modifications to it based on their values

Looking for a Solution Current Data- id price 1001 200 1001 150 1002 300 1003 50 1002 70 1004 30 Desired Outcome id price 1001 350 1002 370 1003 ...

In what ways can I enhance and visually improve JSON data using a jquery/javascript plugin?

My current project requires me to display JSON data received from the backend in a textarea. However, the data comes unformatted and not validated. Now I'm facing two main challenges: 1) How can I beautify the JSON content in the textarea? 2) How can ...

How can I stop popup labels from appearing in MapBox GL JS when I don't want them to be visible?

Having created an application using MapBox GL JS, I have placed numerous markers all around the globe. As the mouse hovers over these markers, a description box pops up, which is what I intended. However, I am encountering an issue where these labels flick ...

Javascript variable capturing only the initial word from a string

Currently, I am working on a simple JavaScript function but my brain seems to be in a fog right now. Any assistance would be greatly appreciated as I suspect there might be a syntax error... The issue I am encountering involves a select value that contain ...

Using a javascript parameter in a cshtml file to filter data in a datatable

Here is the model code public class viewCase { public List<string> lstCategory { get; set; } public DataTable dtWrkTsk { get; set; } } This is the controller code string query = "SELECT WorkFlowID,Subject,Category FROM CMSTasksWorkFlow" ob ...

How can one delete a field from all documents in a collection through Mongoose?

In my MongoDB database, I have a collection of documents that are structured like this: [ { _id: 5fe72e02b237503088b8889b, code: '000001403', name: 'John', date: 2018-12-01T21:00:00.000Z, __v: 1 }, { _id: 5 ...

creating an HTML table from JSON data using a specific key

In this json file, I am looking to create separate tables based on the IDs provided. For example, ID: "50" should be displayed in one table, while ID: "57" should be shown in another table within the same context. { "version": "5.2", "user_type": ...

Mapping Store Fields to JSON Properties in ExtJS: A Complete Guide

I am working with a JSON data object that includes exchange rates information: { "disclaimer": "Exchange rates provided for informational purposes only and do not constitute financial advice of any kind. Although every attempt is made to ensure quality, ...

The `$refs` variable in Vue can be used to reference a specific Vue component within a class-st

Would it be possible to access this.$refs.label? I am using the package vue-property-decorator. Below is the content of the component: <template> <div> <label ref="label">asd</label> </div> </template> <scr ...

Issues with jQuery AJAX functionality and updating a div with JSON results

I am attempting to retrieve data from a database, convert it to JSON, and then display the results within a div that is updated using AJAX triggered by a form submission button labeled Go! Unfortunately, the code is not functioning as expected, and I am a ...

What is the reason behind having a selectedOptions property rather than just a selectedOption?

Why does the selectedOptions property of select return an HTMLCollection instead of just one HTMLOptionElement? As far as I understand (correct me if I'm wrong), a select element can only have one selected option, so why do I always need to access it ...

No more constant reloading every 10 seconds with the jQuery chat application

I am currently working on a chat application where I have a sidebar menu on the left that displays all the people I can chat with. Using JQuery and ajax, I'm able to retrieve messages successfully, however, they only load when I manually click on a co ...

Database with individual queries in each row

I'm in search of a tutorial that can guide me on creating an effective table using AJAX. For instance, I have one table containing user information and another table with records for each user. Users Table UserID | Name =======|=========== 000001 | K ...

Ways to display the result in a new tab

I am using colorbox with a form that will be submitted to another website. I would like for the response from that web page to load in a new tab with a new URL. ...

Validation of Style

Is there a way to translate the following CSS code into JavaScript? Basically, I want it to apply the style rules after the onchange event. .appnitro input:required:valid, .appnitro textarea:required:valid { box-shadow: 0 0 5px #5cd053; border-c ...

Command for controlling volume in DiscordJS

Despite my efforts, I am struggling to write a command that successfully changes the volume of the music being played. Every time the player and resource variables in the volume() function are empty while the bot is playing the song. What can I do to resol ...

Adjusting the style when a link is clicked within a Wordpress loop

I need help isolating and adding a class to a clicked anchor tag that is generated from a Wordpress loop. Currently, my JQuery code removes the "static" class from all tags in the div instead of just the one that was clicked. The active class is added mome ...

After selecting a subitem, the side menu will automatically close

I designed a side menu that expands to reveal submenus. However, when I click on a subitem within a submenu, the entire list closes. The HTML, CSS, and JavaScript code all appear to be correct as the template is functioning properly. But as soon as I ins ...