AngularJS中的友好URL:移除URL中的#
AngularJS 默認(rèn)將會使用一個 # 號來對URL進(jìn)行路由.
例如:
- 
    
http://example.com/
 - 
    
http://example.com/#/about
 - 
    
http://example.com/#/contact
 
要獲得干凈的URL并將井號從URL中移除是很容易的.
完成兩件事情就行了.
- 
    
配置 $locationProvider
 - 
    
設(shè)置我們的相對連接的起點路徑
 
$location 服務(wù)
在Angular中, $location服務(wù)會解析地址欄中的URL,并對你的應(yīng)用程序作出改變,反之亦然.
我強烈推薦通讀官方的 Angular $location 文檔 以對$location 服務(wù)及其所提供的特性有一個了解.
$locationProvider 和 html5 模式(html5Mode)
我們會使用 $locationProvider 模塊,并將html5Mode設(shè)置為true.
我們會在你定義Angular應(yīng)用程序并配置你的路由時做這些.
- 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
 - $locationProvider.html5Mode(true);
 - });
 
什么是 HTML5 History API? 它是使用一個腳本來操作瀏覽器歷史的標(biāo)準(zhǔn)方法. 有了它就能在不刷新頁面的前提下讓 Angular 改變路由和頁面的URL. 更多的信息,這里有一篇蠻好的 HTML5 History API 文章.
為相對鏈接設(shè)置<base>
為了在應(yīng)用程序各處使用相對鏈接,你將需要在你文檔的<head>里面設(shè)置一個<set>.
- <!doctype html>
 - <html>
 - <head>
 - <meta charset="utf-8">
 - <base href="/">
 - </head>
 
有大量的方法可以用來配置這個東西,而將HTML5Mode設(shè)置為true就會自動的解析相對鏈接了. 在我這兒這種方式總是能起效. 如果你應(yīng)用程序的根同url相比有所不同,例如 /my-base, 那就用那個作為你的起點路徑.
老瀏覽器的回調(diào)
$location服務(wù)對不支持HTML5瀏覽歷史API的瀏覽器將自動回調(diào)hashbang方法。
一切的發(fā)生對你是透明的,你不需為此做任何配置。從Angular $location文檔中,你可以看到回調(diào)的方法已經(jīng)它是如何工作的。
總結(jié)
這是一個在Angular應(yīng)用中獲得漂亮URL并刪除哈希標(biāo)記的簡單方法。享受超潔凈、超快速的Angular應(yīng)用吧!
英文原文:Pretty URLs in AngularJS: Removing the #
譯文來自:http://www.oschina.net/translate/pretty-urls-in-angularjs-removing-the-hashtag
















 
 
 



 
 
 
 