Remove the # character in the URL under AngularJS
This article mainly introduces how to remove the # character in the URL under AngularJS. AngularJS is a popular JavaScript library. For more information, see
By default, AngularJS uses a # number to route URLs.
For example:
Http://example.com/
Http://example.com/#/about
Http://example.com/#/contact
It is easy to get a clean URL and remove the well number from the URL.
Just do two things.
Configure $ locationProvider
Set the start path of our relative connection
$ Location service
In Angular, the $ location service parses the URL in the address bar and changes your application, and vice versa.
I strongly recommend that you read the official Angular $ location document to understand the $ location service and its features.
$ LocationProvider and html5 mode (html5Mode)
We will use the $ locationProvider module and set html5Mode to true.
We will do this when you define Angular applications and configure your routes.
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
Angular. module ('scotchy', []) . 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 Optional 5 Mode (true ); }); |
What is HTML5 History API? It is a standard method for operating browser history using a script. with this feature, Angular can change the routing and page URL without refreshing new pages. for more information, here is a good HTML5 History API article.
Set relative links
To use relative links across applications, you need to set .
?
1 2 3 4 5 6 7 |
<! Doctype html> <Html> <Head> <Meta charset = "UTF-8"> <Base href = "/"> </Head> |
There are a lot of ways to configure this thing, and setting HTML5Mode to true will automatically parse the relative link. this method always works for me. if the root of your application is different from the url, for example,/my-base, use that as your starting path.
Old browser callback
$ Location service automatically calls back the hashbang method to browsers that do not support HTML5 browsing history APIs.
Everything is transparent to you, and you do not need to make any configuration for it. From the Angular $ location document, you can see how the callback method works.
Summary
This is a simple method for obtaining beautiful URLs in Angular applications and deleting hash tags. Enjoy the ultra-clean and ultra-fast Angular application!