Angular.js - index template fails to execute controller, but other templates work flawlessly

I am facing a strange issue with my Angular application that uses ngRoute. I have set up different controllers for each template in the routes.js file:

routes.js:

angular.module('PokeApp', ['ngRoute'])
  .config(function($routeProvider){
    $routeProvider
    .when('/', {
      templateUrl: '../templates/template-index.html',
      controller: 'IndexController'
    })
    .when('/products', {
      templateUrl: '../templates/template-products.html',
      controller: 'ProductsController'
    })
    .when('/events', {
      templateUrl: '../templates/template-events.html',
      controller: 'EventsController'
    })
    .otherwise({ redirectTo: '/' });

The controllers are linked in the index.html file like this:

<!-- Scripts -->
<script src="js/angular.min.js"></script>
<script src="js/angular-route.min.js"></script>

<script src="js/routes.js"></script>

<script src="js/controllers/controller-index.js"></script>
<script src="js/controllers/controller-products.js"></script>
<script src="js/controllers/controller-events.js"></script>

Even though my controllers look almost identical, let's take Index and Products as an example:

controller-index.js:

angular.module('PokeApp')
.controller('IndexController', function($scope) {
  // Testing purposes
  console.log("hi");

  ..

});

controller-products.js:

angular.module('PokeApp')
.controller('ProductsController', function($scope) {
  // Again, for testing
  console.log("hi");

  ..

});

The strange part is that when I visit '/', the Index Controller doesn't log anything to the console. There are no typos because if I purposely use the wrong controller name, I get an error in the console.

However, when I go to /products, I do see 'hi' printed as expected.

I have checked everything I can think of - typos, paths, even searched on stackoverflow. I just can't seem to figure out why the Index Controller isn't functioning while the others work perfectly fine.

Could someone please help me troubleshoot this? Thank you for your time.

Answer №1

Have you considered including an additional case in your route provider configuration? For example:


      otherwise({
        redirectTo: '/'
      });

Answer №2

To set the default route, you can do the following:

$routeProvider
    .when('/index', {
        templateUrl: '../templates/template-index.html',
        controller: 'IndexController',
    })
    .otherwise({ redirectTo: '/index' });


I suggest using ui-router from the beginning of your project. It offers all the features of ngRoute and more additional functions.

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

AngularJS UI.Router ActiveState implemented with a dropdown menu feature

I am currently working on creating a menu with dropdown functionality for multiple links within my application. My goal is to have the dropdown menu display as "active" when one of the links below is active. I have managed to make either the link in the ...

How can I create a new PHP table using data from an existing table?

I have a table displayed on my website with the code snippet providedview the table image here Here is the code for generating this table: <?php $query = $db->query("SELECT * FROM bit_exchanges ORDER BY id DESC LIMIT 20"); if($query-> ...

What's the best way to add line numbers to source code on an HTML webpage after parsing?

I am currently working with AngularJS and MongoDB. In my MongoDB data, there are some text elements that contain a \n, causing each line to be displayed on a new line based on the occurrence of \n. However, I also want to add line numbers to each ...

transform data into JSON format and transmit using jquery ajax

I have one object: var myobject = {first: 1, second: {test: 90}, third: [10, 20]}; and I need to convert it into a JSON string using jQuery ajax. Can someone please advise on how to achieve this? (I tried using JSON.stringify(), but it didn't work ...

Is there a way to set up a listener for a particular property of a recoil state object?

Is it possible to create a listener for a specific property within a state object? Let's look at an example: type ExampleAtomProperties = { id: number; description: string; }; const ExampleAtom = atom< ExampleAtomProperties>({ key: &quo ...

What is the best way to use jQuery AJAX to make changes to an HTML element that will be permanent even after the page is refreshed?

Starting out with codeigniter, I am working on building an ecommerce website. Every time a user clicks the "Add to cart" button in my view, I utilize jquery ajax to send a request to a controller function. This function then returns two variables: count ( ...

unorthodox method of transmitting parameters within express.js source code

While searching for the source code of express router, I came across this interesting piece: var debug = require('debug')('express:router:route'); I am curious to know more about this unusual way of passing arguments. Can someone ...

Information regarding gender vanishes upon refreshing the page

When the page is refreshed, the variable called jso disappears. Is there an alternative method for storing information that does not involve using a button? The goal is to have it work seamlessly when the page is reloaded without requiring any user action. ...

Retrieve data via AJAX using a combination of JavaScript and ASP

Can someone help me figure out how to retrieve the value of value1 on my server-side ASP using Javascript? I am using this Ajax code but unsure of how to do it. In my serverside code, I would like to have something like <% var newdata = value1 (which ...

Unable to transfer the properties of reactjs to react-chartist

How can I pass the state from the parent component "main.js" into the child component "bar.js"? //main.js import React, { Component } from 'react'; import BarChart from './Bar-chart'; class Hero extends Component { cons ...

The material-ui library always registers Event.ctrlKey as true

When using the Table Component from the material-ui library, I encountered an issue with the multiSelectable feature. Setting the value of multiSelectable to true allows for multiple selections, but the behavior is not what I expected. By default, the sel ...

Trouble with triggering HTML5 FileReader() functions

I'm having trouble determining why neither readSuccess() nor readFailure() are being executed in the code snippet below: function readMyFile(){ var reader = new FileReader(); reader.onload = readSuccess; reader.onerror = readFailure; ...

Switching up the Label Colors in Chart.JS

It's been a while since my last question, so please bear with me if I'm not following the rules. I've attached my current code and a reference image of the chart. I am completely new to working with ChartJS. The situation is a bit unique: t ...

Unable to locate element using Protractor

I'm struggling with getting protractor to work correctly when testing my angular app. The code in my spec file is as follows: describe('app login', function() { it('should allow admin user to log in', function() { browse ...

Steps to retrieve data (token) from developer tools and incorporate it into a fetch Post request

Is there a simple way to extract data using dev tools and insert it into a fetch request? I am trying to make a POST request through the console, but I am struggling to correctly copy a token. I attempted to use querySelector but instead of finding the t ...

Utilizing jQuery Ajax to submit multiple forms using a single selector in one go

I'm having an issue with jQuery Ajax involving multiple forms. Each time I execute it, only the top form works properly while the others do not function as expected. Can anyone provide assistance with this? Here is the source code: <form id="form_ ...

Sending data to and retrieving data from a server

Just a quick query. I've been using ajax POST and GET methods to send JSON data to a server and then fetch it back. However, I'm facing some confusion while trying to extract JSON information from the GET call. getMessage = function(){ $.ajax ...

determining the quantity of dates

Is there a way to calculate the number of a specific day of the week occurring in a month using AngularJS? For example, how can I determine the count of Saturdays in a given month? Thank you. Here is the code snippet I have been working on: <!doctype ...

Stringification will not work on the virtual object that has been populated

Here is the object passed to the view: app.get('/view_add_requests', isLoggedIn, function (req, res) { var my_id = req.user._id; // this is the senders id & id of logged in user FriendReq.find({to_id: my_id}).populate('prof ...

Managing the re-rendering in React

I am encountering a situation similar to the one found in the sandbox example. https://codesandbox.io/s/react-typescript-fs0em My goal is to have Table.tsx act as the base component, with the App component serving as a wrapper. The JSX is being returned ...