Skip to content Skip to sidebar Skip to footer

Angularjs Auto Prefixes Forward Slash

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 i

Solution 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).


Solution 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


Post a Comment for "Angularjs Auto Prefixes Forward Slash"