Kushal
Kushal

Reputation: 23

html5mode does not remove hashbang mode in angularjs

I am trying to create an SPA in AngularJS using ngRoute. To do so, I have enabled HTML5 mode to remove the # from the URL. However, when I navigate to a different route (e.g., /about or /contact), the content does not change, and only the home page is displayed, the URL also has a #%2F in front. Refreshing the page on a non-root route (e.g., /about) gives a 404 error.

Here’s what I have done so far:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AngularJS SPA</title>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.3/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.3/angular-route.min.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

    <script type="text/javascript" src="scripts/index.js"></script>
    <script type="text/javascript" src="scripts/routes.js"></script>

    <base href="/">
</head>

<body ng-app="sample">

    <nav>
        <a href="#/">Home</a>
        <a href="#/about">About</a>
        <a href="#/contact">Contact</a>
    </nav>

    <div ng-view></div>

</body>
</html>

var app = angular.module("sample", ["ngRoute"]);
app.config(function ($routeProvider, $locationProvider) {
    $routeProvider
        .when("/", {
            templateUrl: "templates/home.html",
        })
        .when("/about", {
            templateUrl: "templates/about.html",
        })
        .when("/contact", {
            templateUrl: "templates/contact.html",
        })
        .otherwise({
            redirectTo: "/"
        });
    // $locationProvider.hashPrefix('');
    $locationProvider.html5Mode(true);
});

Issue I am facing: Whenever I click on a link, such as "About," the URL changes to http://localhost:8000/#%2Fabout, but only the home page content remains visible.

How can I make the AngularJS route changes properly reflect the corresponding template?

Upvotes: 0

Views: 23

Answers (1)

bgajic-mono
bgajic-mono

Reputation: 16

Your href properties start with "#/", remove the starting hash (%2F is encoded /) and try again.

<nav>
    <a href="#/">Home</a>
    <a href="#/about">About</a>
    <a href="#/contact">Contact</a>
</nav>

Upvotes: 0

Related Questions