0

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?

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.