Troubaling with AngularJS Routing issues

I am encountering an issue with my routing system. The "otherwise" case is functioning correctly, however, when I click on a menu item, the routing does not load the corresponding page automatically. Can someone assist me in identifying what is wrong with my code?

Below is the code related to the routing section:

var myColors = angular.module('myFirstModule', ['ngRoute']);
myColors.config(['$routeProvider', function($routeProvider) {
  $routeProvider
    .when('/home', {
      templateUrl: 'home.html'
    })
    .when('/directory', {
      templateUrl: 'directory.html',
      controller: 'myFirstModule'
    }).otherwise({
      redirectTo: '/directory'
    });
}]);

Here is the HTML div where I have added the links:

<ul>
    <li><a href="#/home">Home </a></li>
    <li><a href="#/directory">Directory</a></li>
</ul>    

Here is a Plunker showcasing my complete code

Answer №1

For users of AngularJS 1.6, make sure to include an exclamation mark (!) in your href routing.
For example, href="#/home" should be changed to href="#!/home".

<ul>
    <li><a href="#!/home">Home</a></li>
    <li><a href="#!/directory">Directory</a></li>
</ul>    

To remove this prefix, refer to this answer.

Answer №2

The controller name you are using is incorrect and as @Mistalis pointed out, you need to include #! in your href. If you wish to remove the !, simply use

$locationProvider.hashPrefix('');
in your config. Then you can use your href without !

JS

var myColors = angular.module('myFirstModule', ['ngRoute']);
myColors.config(['$routeProvider', function($routeProvider) {
  $routeProvider
    .when('/home', {
      templateUrl: 'home.html'
    })
    .when('/directory', {
      templateUrl: 'directory.html',
      controller: 'myFirstController' //insert your controller name here
    }).otherwise({
      redirectTo: '/directory'
    });
}]);

HTML

<ul>
    <li><a href="#!/home">Home </a></li>
    <li><a href="#!/directory">Directory</a></li>
</ul> 

Working Plunker: https://plnkr.co/edit/GAob2u4MdnzXXltTZMg2?p=preview

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

Creating a unique-looking visual representation of progress with arcs

Looking to create a circular progress bar (see image below), with loading starting from the left bottom side up to the right bottom side. The empty state should be light-blue (#E8F6FD) and the progress color strong blue (#1CADEB). https://i.sstatic.net/VZ ...

I am looking for a way to connect a saved phone number with a Vue tel input so that I can make changes

Currently, I am utilizing vue-tel-input to input a phone number. Below is the code snippet: <template> <div> <vue-tel-input v-model="client.ClientPhone" v-bind="bindPropsUserInfo"></vue-tel-input> </div> ...

My confidential environment variables are being inadvertently revealed to the client by Next.js

I am encountering a problem with my project in which an environment variable is being revealed to the browser. Despite the documentation stating that only environment variables prefixed with NEXT_PUBLIC_ should be accessible in the browser environment, all ...

Transferring sizable JavaScript array to the Web API

I've been grappling with this problem for two days... In my JavaScript code, I have a large array comprising 20,000 rows and 41 columns. This data was initially fetched in JavaScript via an ajax call, as shown below: var dataArray = []; var dataRequ ...

The compatibility of ng-switch-when and ng-class

Is it possible to use ng-switch-when and ng-class together on the same element without any compatibility issues? I am facing some trouble dynamically changing the class of multiple elements simultaneously. It seems to only work on the currently displayed e ...

Prevent AngularJS UI Router view from refreshing upon tab change

In my application, I am utilizing AngularJS UI routing to implement tabs for a better user experience. There are several tabs within the application, each containing various input fields. One issue I am facing is that whenever a user switches tabs whil ...

Is it possible for me to include detailed information to a particular attribute of an object?

Although the code below is incorrect, it reflects my intention. Can this be achieved? I am looking to update the original array so that all orderno values are formatted as 000.0.000.00000.0. let cars= [ {orderno: "5766302385925", make: "Alfa", dealersh ...

Is jQuery Mobile Autocomplete's search feature activated after typing 3 letters?

Hello there, I am in the process of creating a website and have implemented an autocomplete field. However, I am facing an issue due to having over 1000 <li> elements within the <ul>, making it slow especially on mobile devices. I would like t ...

Do I need to make any changes to the application when adding a new couchbase node to the cluster

Currently, I am utilizing the Node.js SDK to establish a connection with a couchbase cluster. Despite this, in the Node.js documentation, there is no clear instruction on how to input multiple IP addresses (of cluster nodes) when creating the cluster objec ...

Employing a factory for transferring information between controllers in AngularJS

I am working on passing longitude and latitude values using the Google Maps API from one controller to another. I am utilizing a factory to achieve this, but encountering issues with either sending the information to the factory or retrieving it from there ...

What is the significance of the error message "Uncaught (in promise) Object"?

I am facing an error in my code and need help to correct and debug it. I would like the code execution to halt when an issue arises. Here is my code snippet: export function postRequestOtpCode(phone: string, token: string): CancellableAxiosPromise { ax ...

What is the best way to distinguish between various objects that are all in a single line?

After creating an array of objects with data such as name and id, I used the res.json() method to convert it into json format for browser use. However, when I input the array of object data, it looked like this: [ { id: 1, name: 'albany sof ...

Error: Issue transferring data to controller from Ng-Style

Currently, I am developing an application using Ionic and AngularJS. In this project, I am using ng-repeat to populate the results and want to display different colors based on certain criteria. Initially, I managed to achieve this using inline ng-style c ...

Creating reversed/generate URLs from Routes in Angular2 (using typescript)

Is there a way to automatically create a URL from a route using code? For instance, let's say I have a login component defined in my routes: const appRoutes: Routes = [ ... { path: 'login', component: LoginComponent }, ... ]; N ...

I need help figuring out how to get a horizontal scrollbar positioned at the top of a div to function properly once the content has been loaded using ajax

HTML CODE <div id="scrollidout" style="overflow: auto; overflow-y: hidden; "> <div id="scrollidin" style="padding-top: 1px; height: 20px; width: 1000px">&nbsp;</div> </div> <div class="resultcontent" style="overflow ...

Using JavaScript to Parse JSON with Carriage Returns and Line Breaks

Utilizing the script below in JavaScript, I am able to extract a JSON string from a different JS file: // code to retrieve JSON data from another JS module var jsonMatch = data.match( /\/\*JSON\[\*\/([\s\S]*?)\/&bso ...

Dialog in Angular Material refuses to close even after calling the dialog.close() function

I've been struggling with this issue for a while, hoping someone can assist. In my Angular project, I have a login component with a dialog that opens a new popup window. Upon successful login, this window closes and triggers the following function: l ...

Execute JavaScript function only if it is the final invocation

I'm currently experiencing an issue with a Javascript function that updates a bootstrap spinner. The function works well in general, but the problem arises when I click multiple times. I utilize ajax to update the quantity of selected products in the ...

Waiting for all promises to resolve: A step-by-step guide

I need to make two different API calls and perform calculations based on the results of both. To wait for both promises to resolve, I am using Promise.all(). const getHashTagList = async () => { loader.start(); try { await getAllHashTag ...

Can you provide guidance on displaying flash messages in my template using Express.js?

app.get('/',function(req,res){ res.render('home'); // Ensure the template has access to the flash message }); app.get('/go',function(req,res){ req.flash("info", "You have gone to GO and got redirected back home!"); ...