Angularjs auto prefixes forward slash

All we need is an easy explanation of the problem, so here it is.

If I hit the url say

www.xyz.com/home#route-1

AngularJS automatically re-directs it to

www.xyz.com/home#/route-1

That is – it prefixes the route with a / (forward slash)

Why is it happening and how can I stop making it do this?

Update
What I am really looking for is that angular should not attach the forward slash neither remove the hash sign.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

@Tushar I’m not sure if you’ve figured out a solution but I came across your scenario too and no luck with googling. Eventually I figured out it’s a rather simple fix, I’ve added : –

angular.config(function($locationProvider) {
    $locationProvider.html5Mode({
        enabled: true,
        requireBase: false,
        rewriteLinks: false
    });
})

And it just stop appending the forward slash (/) prefix to my hash anchor. Everything remains as what we’re familiar with (no replacing of URL with hash or what-not).

Method 2

If you want to use an anchor in your AngularJS app, you should use the $anchorScroll service.

"controller"

function ScrollCtrl($scope, $location, $anchorScroll) {
  $scope.gotoBottom = function (){
    // set the location.hash to the id of
    // the element you wish to scroll to.
    $location.hash('bottom');

    // call $anchorScroll()
    $anchorScroll();
  }
}

"html"

<div id="scrollArea" ng-controller="ScrollCtrl">
  <a ng-click="gotoBottom()">Go to bottom</a>
  <a id="bottom"></a> You're at the bottom!
</div>

You could see this working in AngularJS documentation.

If you want to prettify AngularJS urls you could enabled html5Mode:

.config(function($routeProvider, $locationProvider) {

    $routeProvider
        .when('/', {
            templateUrl : 'partials/home.html',
            controller : mainController
        })
        .when('/about', {
            templateUrl : 'partials/about.html',
            controller : mainController
        })
        .when('/contact', {
            templateUrl : 'partials/contact.html',
            controller : mainController
        });

    // use the HTML5 History API
    $locationProvider.html5Mode(true);
});

You could see more here

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply