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

來源:互聯網
上載者:User

移除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文檔中,你可以看到回調的方法已經它是如何工作的。

  總結

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.