Search code examples
javascripthtmlangularjsmean-stackhashbang

AngularJS SPA routing getting URL as "/#!" instead of "#"


In my SPA AngularJS application, I am getting the URL as http://localhost:4200/#!/ instead of just # (hash bang). Because of this the routing does not seem to work in the usual way. I did go through this stackoverflow Question but did not find any solution.Anybody knows the solution to get rid of this extra exclamation mark?

EDIT: In my index.ejs: I have <a href="#about">about</a>

In my approutapp.js: I have

var myapp = angular.module("myApp", ["ngRoute"]);
myapp.config(function($routeProvider) {
    $routeProvider
    .when("/", {
        templateUrl : "/static/list.ejs"
    })
    .when("/about", {
        templateUrl : "/static/about-us.ejs"
    })

});

myapp.config(['$locationProvider', function($locationProvider) {
  $locationProvider.hashPrefix('');
}]);

But the URL which I am still getting: http://localhost:4200/#/!/

and going to http://localhost:4200/about the page hangs


Solution

  • Try using $locationProvider.hashPrefix('')

    The reason is:

    If the browser is HTML5 browser angularJS will redirect it to #!

    Otherwise it will be only #.

    Read this documentation on $location to find out more on this:

    Opening a regular URL in a legacy browser -> redirects to a hashbang
    
    URL Opening hashbang URL in a modern browser -> rewrites to a regular URL 
    

    HTML5 mode

    In HTML5 mode, the $location service getters and setters interact with the browser URL address through the HTML5 history API. This allows for use of regular URL path and search segments, instead of their hashbang equivalents. If the HTML5 History API is not supported by a browser, the $location service will fall back to using the hashbang URLs automatically. This frees you from having to worry about whether the browser displaying your app supports the history API or not; the $location service transparently uses the best available option.

    Opening a regular URL in a legacy browser -> redirects to a hashbang URL Opening hashbang URL in a modern browser -> rewrites to a regular URL Note that in this mode, AngularJS intercepts all links (subject to the "Html link rewriting" rules below) and updates the url in a way that never performs a full page reload.