萬盛學電腦網

 萬盛學電腦網 >> 腳本專題 >> javascript >> 移除AngularJS下URL中的#字符的方法

移除AngularJS下URL中的#字符的方法

   這篇文章主要介紹了移除AngularJS下URL中的#字符的方法,AngularJS是一款高人氣JavaScript庫,需要的朋友可以參考下

  AngularJS 默認將會使用一個 # 號來對URL進行路由.

  例如:

  http://example.com/

  http://example.com/#/about

  http://example.com/#/contact

  要獲得干淨的URL並將井號從URL中移除是很容易的.

  完成兩件事情就行了.

  配置 $locationProvider

  設置我們的相對連接的起點路徑

  $location 服務

  在Angular中, $location服務會解析地址欄中的URL,並對你的應用程序作出改變,反之亦然.

  我強烈推薦通讀官方的 Angular $location 文檔 以對$location 服務及其所提供的特性有一個了解.

  $locationProvider 和 html5 模式(html5Mode)

  我們會使用 $locationProvider 模塊,並將html5Mode設置為true.

  我們會在你定義Angular應用程序並配置你的路由時做這些.

  ?

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 $locationProvider.html5Mode(true); });

  什麼是 HTML5 History API? 它是使用一個腳本來操作浏覽器歷史的標准方法. 有了它就能在不刷新頁面的前提下讓 Angular 改變路由和頁面的URL. 更多的信息,這裡有一篇蠻好的 HTML5 History API 文章.

  為相對鏈接設置

  為了在應用程序各處使用相對鏈接,你將需要在你文檔的裡面設置一個.

  ?

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

  有大量的方法可以用來配置這個東西,而將HTML5Mode設置為true就會自動的解析相對鏈接了. 在我這兒這種方式總是能起效. 如果你應用程序的根同url相比有所不同,例如 /my-base, 那就用那個作為你的起點路徑.

  老浏覽器的回調

  $location服務對不支持HTML5浏覽歷史API的浏覽器將自動回調hashbang方法。

  一切的發生對你是透明的,你不需為此做任何配置。從Angular $location文檔中,你可以看到回調的方法已經它是如何工作的。

2015619153430123.jpg (567×311)

  總結

  這是一個在Angular應用中獲得漂亮URL並刪除哈希標記的簡單方法。享受超潔淨、超快速的Angular應用吧!

copyright © 萬盛學電腦網 all rights reserved