Angular.js app: eliminate #! from the URLs of my single posts while keeping the slug

Issue

I am working on a small AngularJS blogging app (the framework version I use is 1.7.8).

I have managed to pull and display posts from an API I made myself.

I got stuck trying to eliminate #! from the URLs of my single posts while keeping the slug.

Example:

I have http://examplesite.eu/#!/europes-most-beautiful-castles and I tried to get http://examplesite.eu/europes-most-beautiful-castles.

This solution from the AngularJS docs does not work, as it completely eliminates the slug, and I want to keep it, for SEO purposes:

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

My app.js file:

angular.module('app', [
    'ngRoute',
    'app.controllers',
    'ngSanitize'
]).config(['$routeProvider', function($routeProvider){
    $routeProvider.when('/', {
        templateUrl: 'templates/posts.html',
        controller: 'PostsController'
    }).when('/:slug', {
        templateUrl: 'templates/singlepost.html',
        controller: 'SinglePostController'
    }).when('/page/:id', {
        templateUrl: 'templates/page.html',
        controller: 'PageController'
    }).otherwise({
        redirectTo: '/'
    });
}]);

What’s an alternative that would keep the slug in the post URL?

Solution

You need to use $locationProvider.html5mode to switch over to the history api so that angular can manipulate the URL more directly rather than using hashes.

You can read more about it in the documentation Hashbang and HTML5 Modes

Answered By – kicken

Answer Checked By – Clifford M. (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.