AngularJS中的友好URL:移除URL中的#

开发 前端
这是一个在Angular应用中获得漂亮URL并删除哈希标记的简单方法。享受超洁净、超快速的Angular应用吧!

AngularJS 默认将会使用一个 # 号来对URL进行路由.

例如:

  • http://example.com/

  • http://example.com/#/about

  • http://example.com/#/contact

要获得干净的URL并将井号从URL中移除是很容易的.

完成两件事情就行了.

  1. 配置 $locationProvider

  2. 设置我们的相对连接的起点路径

$location 服务

在Angular中, $location服务会解析地址栏中的URL,并对你的应用程序作出改变,反之亦然.

我强烈推荐通读官方的 Angular $location 文档 以对$location 服务及其所提供的特性有一个了解.

$locationProvider 和 html5 模式(html5Mode)

我们会使用 $locationProvider 模块,并将html5Mode设置为true.

我们会在你定义Angular应用程序并配置你的路由时做这些.

  1. angular.module('scotchy', [])  
  2.       
  3.     .config(function($routeProvider, $locationProvider) {  
  4.  
  5.         $routeProvider  
  6.             .when('/', {  
  7.                 templateUrl : 'partials/home.html',  
  8.                 controller : mainController  
  9.             })  
  10.             .when('/about', {  
  11.                 templateUrl : 'partials/about.html',  
  12.                 controller : mainController  
  13.             })  
  14.             .when('/contact', {  
  15.                 templateUrl : 'partials/contact.html',  
  16.                 controller : mainController  
  17.             });  
  18.       
  19.         // use the HTML5 History API  
  20.         $locationProvider.html5Mode(true);  
  21.     });  

什么是 HTML5 History API? 它是使用一个脚本来操作浏览器历史的标准方法. 有了它就能在不刷新页面的前提下让 Angular 改变路由和页面的URL. 更多的信息,这里有一篇蛮好的 HTML5 History API 文章.

为相对链接设置<base> 

为了在应用程序各处使用相对链接,你将需要在你文档的<head>里面设置一个<set>.

  1. <!doctype html> 
  2. <html> 
  3. <head> 
  4.     <meta charset="utf-8"> 
  5.  
  6.     <base href="/"> 
  7. </head> 

有大量的方法可以用来配置这个东西,而将HTML5Mode设置为true就会自动的解析相对链接了. 在我这儿这种方式总是能起效. 如果你应用程序的根同url相比有所不同,例如 /my-base, 那就用那个作为你的起点路径.

老浏览器的回调

$location服务对不支持HTML5浏览历史API的浏览器将自动回调hashbang方法

一切的发生对你是透明的,你不需为此做任何配置。从Angular $location文档中,你可以看到回调的方法已经它是如何工作的。

hashbang_vs_regular_url

总结

这是一个在Angular应用中获得漂亮URL并删除哈希标记的简单方法。享受超洁净、超快速的Angular应用吧!

英文原文:Pretty URLs in AngularJS: Removing the #

译文来自:http://www.oschina.net/translate/pretty-urls-in-angularjs-removing-the-hashtag

责任编辑:林师授 来源: 开源中国社区 编译
相关推荐

2011-05-11 14:50:54

URL

2021-04-16 20:50:16

URL爬虫参数

2009-07-31 09:58:20

URL映射ASP.NET

2021-08-30 23:47:28

URLQuery字段

2010-10-25 10:13:16

ibmdwWebSphere

2023-02-01 14:08:53

JavaScriptURL安全

2009-07-22 14:23:39

URL RewriteASP.NET

2009-07-23 16:28:20

URL映射ASP.NET 2.0

2010-05-11 14:30:39

2009-01-04 13:27:10

URL RewriteIISASP.NET

2010-05-11 13:07:23

Mysql JDBC

2009-10-26 15:55:43

URL Routing

2020-10-28 08:10:27

URL域名https

2009-07-24 11:20:43

ASP.NET MVC

2009-09-24 09:26:22

ASP.NET MVC

2021-10-10 18:29:27

URL编码Go

2009-07-07 10:14:57

基于URL权限控制

2021-03-02 07:31:26

WebApiweb

2022-06-30 12:43:53

Firefox隐私功能URL

2016-09-27 21:14:53

JavaURL
点赞
收藏

51CTO技术栈公众号