Error: Unrecognized controller in AngularJS/Ruby on Rails framework

I've been working through the tutorial on implementing an Angular JS / Ruby on Rails app from Thinkster and have encountered a problem.

Despite my controllers being listed in the page's sources when inspecting the content, they are not being recognized. This issue is noted in the console error message:

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

I've exhaustively searched online for solutions without success. At this point, I suspect it might be related to the version of Angular or Rails, a gem, dependency, or something that has eluded me. It could even be a simple typo that I am overlooking!

As a result, the page loads blank except for the content in the navigation bar, which appears without any controller logic. I will provide some code below, and if further information is required for a solution, please let me know.

This is the snippet from application.html.erb:

<!DOCTYPE html>
<html>
<head>
  <title>Angular JS</title>
  <%= stylesheet_link_tag    'application', media: 'all' %>
  <%= javascript_include_tag 'application' %>
  <%= csrf_meta_tags %>
</head>
<!-- body -->
  <body ng-app="flapperNews">
    <div class="row">
      <div class="col-md-6 col-md-offset-3">
        <div ng-include="'nav/_nav.html'"></div>
        <ui-view></ui-view>
      </div>
    </div>
    <h1>DEBUG</h1>
  </body>
</html>

The following code is from app.js, which includes the app module and view configuration:

angular.module('flapperNews', ['ui.router', 'templates', 'Devise'])
.config([ 
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {

  $stateProvider
    .state('home', {
      url: '/home',
      templateUrl: 'home/_home.html',
      controller: 'MainCtrl'
    }) 
    .state('posts', {
      url: '/posts/{id}',
      templateUrl: 'posts/_posts.html',
      controller: 'PostsCtrl'
    })
    .state('login', {
      url: '/login',
      templateUrl: 'auth/_login.html',
      controller: 'AuthCtrl',
      onEnter: ['$state', 'Auth', function($state, Auth) {
        Auth.currentUser().then(function (){
          $state.go('home');
        });
      }]
    }) 
    .state('register', {
      url: '/register',
      templateUrl: 'auth/_register.html',
      controller: 'AuthCtrl',
      onEnter: ['$state', 'Auth', function($state, Auth) {
        Auth.currentUser().then(function (){
          $state.go('home');
        });
      }]
    });

  $urlRouterProvider.otherwise('home');
}]);

It's important to mention that between the two files above,

<div ng-include="'nav/_nav.html'"></div>
at least displays some Angular content, while <ui-view></ui-view> remains empty (irrelevant link).

Now, here's the missing piece - navCtrl.js:

angular.module('flapperNews')
.controller('NavCtrl', [
'$scope',
'Auth',
function($scope, Auth){
  console.log('nav controller loaded');
  $scope.signedIn = Auth.isAuthenticated;
  $scope.logout = Auth.logout;
  Auth.currentUser().then(function (user){
    $scope.user = user;
  });
  $scope.$on('devise:new-registration', function (e, user){
    $scope.user = user;
  });

  $scope.$on('devise:login', function (e, user){
    $scope.user = user;
  });

  $scope.$on('devise:logout', function (e, user){
    $scope.user = {};
  });
}]);

After examining the console, timeline, and sources, it seems that all the necessary files are loading in the correct order. Please assist me with resolving this issue!

Thank you, Steve.

Answer №1

It appears that the code is missing the 'resolve: {....}' section in both .state('posts' and .state('home'. Please make sure to include it for proper functionality.

.state('home', {
        url: '/home',
        templateUrl: 'home/_home.html',
        controller: 'MainCtrl',
        resolve: {
            postPromise: ['posts', function(posts){
                return posts.getAll();
                }]
            }
    })
    .state('posts', {
        url:'/posts/{id}',
        templateUrl: 'posts/_posts.html',
        controller:'PostCtrl',
        resolve: {
            post: ['$stateParams', 'posts', function($stateParams, posts) {
                return posts.get($stateParams.id);
                }]
            }
    })

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

Eliminate repeat entries in MongoDB database

Within our MongoDB collection, we have identified duplicate revisions pertaining to the same transaction. Our goal is to clean up this collection by retaining only the most recent revision for each transaction. I have devised a script that successfully re ...

Revamp the design of the Google image layout

I am trying to replicate the layout of a Google search results page. My goal is to have a full-width div appear on screen when an image is clicked, with a small triangle at the bottom of the clicked image. I attempted to place the img inside another div, ...

Three.js - implementing a billboard effect that preserves orientation through camera pans

My situation involves a plane geometry that always faces the camera using the following line of code in the update loop: plane.lookAt(camera.position); While I am utilizing OrbitControls to manipulate the camera, the plane successfully maintains its orie ...

Vulnerability protection against AngularJS JSON is not removed

I am currently working on an Angular app that communicates with an API. The JSON responses from the API are prefixed with )]}', as recommended in Angular's official documentation. The issue I am facing is that my browser seems to try decoding th ...

Create a lockscreen feature in AngularJS that becomes active after a period of inactivity

I am looking to integrate a lockscreen feature into my app using Angular.js. This lockscreen will consist of a route and an HTML template containing a form that prompts the user to re-enter their password in order to keep their session active. The purpose ...

Replace the ngOnDestroy method

Is there a way to complete an observable when the ngOnDestroy is triggered? I'd prefer not to create new child components when dealing with just one component instance. I attempted to override ngOnDestroy by modifying the function in the component&apo ...

Having trouble importing d3.js and typescript in IntelliJ?

Encountering errors in browsers' console when utilizing d3.select() in typescript code. Despite trying alternative methods like d3-timer.now(), the issue persists. As a newcomer to typescript, I am utilizing intelliJ Ultimate 2019.1. Through npm, I h ...

Tips for ensuring an element is visible in CUCUMBER JS?

Whenever I run my code, it keeps returning the error message: NoSuchElementError: no such element: Unable to locate element Even though I have set up a wait function, it does not seem to actually wait. The step fails immediately without waiting for the s ...

Setting up a local development environment for AngularJS

I have been using the boilerplate https://github.com/node90/angular-starter as a foundation for my projects. However, I've noticed that the repository utilizes gulp to consolidate the js files in the 'app' folder into the 'public/js&apo ...

Utilizing Input Data from One Component in Another - Angular4

As a newcomer to Angular, I'm facing an issue where I need to access a variable from ComponentA in ComponentB. Here's the code snippet that demonstrates what I'm trying to achieve (I want to utilize the "favoriteSeason" input result in the " ...

Using TypeScript to type styled-system props

Currently, I am utilizing styled-system and one of the main features of this library is its shorthand props that allow for simple and quick theming. Although I have streamlined my component, a significant aspect lies here: import React from 'react&a ...

The error message "invalid date" is appearing while trying to calculate the time difference with moment.js

I'm having trouble figuring out the time difference in hours and minutes between two form fields. I keep getting an error message saying "Invalid Date." I've attempted to modify other examples to fit my requirements, but without success. The inpu ...

Utilizing AJAX to send a parameter to PHP for processing

I am facing an issue with a script that is supposed to send data to a PHP file when a user clicks on an element, but unfortunately, it's not functioning correctly. Below is the jQuery code: jQuery( document ).ready(function( $ ) { $('.rve_b ...

Python's method for passing an array to a Django template

If I had an array in my Python backend and needed to send it to the front end as JSON or a JavaScript array, how could I accomplish this utilizing the Django framework? A possible template implementation is as follows: <script type="text/javascript"&g ...

When a function is transferred from a parent component to a child component's Input() property, losing context is a common issue

I have encountered an issue while passing a function from the parent component to the child component's Input() property. The problem arises when the parent's function is called within the child component, causing the this keyword to refer to th ...

Adjust the color of the text inside an array using Angular

We are currently working with nested data that is being displayed in a table. Within one of the table cells, there is an array whose contents are turned into a single string. This transformation relies on an answer found here: Using comma as list separato ...

Tips for retrieving data from a nested Axios request?

Currently, I am working on a series of steps: Phase 1: Initiate an Axios call to verify if the record exists in the database. Phase 2: In case the record does not exist, trigger a POST API call to establish the data and retrieve the POST response. Pha ...

What is the best way to save high-resolution images created with HTML5 canvas?

Currently, there is a JavaScript script being used to load and manipulate images using the fabricjs library. The canvas dimensions are set to 600x350 pixels. When smaller images are uploaded onto the canvas and saved as a file on disk, everything works c ...

What is the process for integrating a factory into a controller?

Hello, I'm currently new to working with angularjs and I'm facing some challenges while trying to inject a factory into my controller. The factory seems to be functioning properly as I can set data in it without any issues. Below is the code snip ...

What is the process for updating the values of Kendo Grid row elements by utilizing data from an external combobox?

I am currently working with a kendo grid that utilizes the roweditor function, allowing users to edit values of networks labeled as network1, network2, and network3 within the grid - let's refer to this as gridNetwork. On the same page, there is also ...