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?
3
Answers
I have managed clean-up the URLs by using the
$locationProvider
service:My app.js file:
In index.html I added
<base href="/">
: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
Try below code: