angularjsngroutehtml5mode

AngularJS about page with html5mode page refresh error


I am using w3schools route example to make a simple website. my project folder is wamp/www/angular/7 and base href="/angular/7/". But when I refresh my page on angular/7/red page refresh shows NOT Found. Kindly advice or correct my mistake, following is the code.

<!DOCTYPE html>
<html ng-app="myApp">
<base href="/angular/7/">
<!--script>document.write('<base href="' + document.location + '" >');</script-->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>
<body>
    <a href="./">Main</a> | <a href="./red">Red</a> | <a href="green">Green</a> | <a href="blue">Blue</a>
    <div ng-view></div>
    <script src="script.js"></script>
</body>
</html>

var app = angular.module("myApp", ["ngRoute"]);
document.getElementsByTagName("base")[0].href = location.href;
app.config(function($routeProvider, $locationProvider) {
    $locationProvider.html5Mode(true).hashPrefix('!');
    $routeProvider
    .when("/", {
        templateUrl : "template/main.html",
        controller : "mainController"
    })
    .when("/red", {
        templateUrl : "template/red.html",
        controller : "redController"
    })
    .when("/green", {
        templateUrl : "template/green.html",
        controller : "greenController"
    })
    .when("/blue", {
        templateUrl : "template/blue.html",
        controller : "blueController"
    });
});

app.controller("mainController", function ($scope) {
    $scope.msg = "Main Page";
});

app.controller("redController", function ($scope) {
    $scope.msg = "Red Page";
});

app.controller("greenController", function ($scope) {
    $scope.msg = "Green Page";
});

app.controller("blueController", function ($scope) {
    $scope.msg = "Blue Page";
});

pages are index.html, red.html, green.html, blue.html, main.html

.htaccess code

<ifModule mod_rewrite.c>
RewriteEngine on
# Don't rewrite files or directories
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^ angular/7/index.html [L]
</ifModule>

Solution

  • You need URL rewriting so that any url that starts with /angular/7 and is not a file or directory is rewritten to /wamp/www/angular/7/index.html

    Search for [your server software] SPA (single page app) rewrite. If you use Apache, that can be done with a .htaccess file, and you need to enable mod-rewrite.