AngularJs $location 和 $window


$location

$location服務解析瀏覽器地址中的url(基於window.location)並且使url在應用程序中可用。將地址欄中的網址的變化反映到$location服務和$location的變化反映到瀏覽器地址欄。

公開瀏覽器地址欄中的當前網址,這樣就可以:

1.觀察和監聽網址。

2.改變網址。

與瀏覽器url同步當用戶:

1.改變地址欄的值。

2. 單擊“后退”或“前進”按鈕(或單擊“歷史鏈接”)。

3.點擊鏈接。

表示一組方法(協議、主機、端口、路徑、搜索、哈希值)的網址對象。

依賴:$rootElement

方法

absUrl();

只能getter,返回的是完整的url。

url([url],[replace]);

getter/setter,返回當前url路徑(當前url#后面的內容,包括參數和哈希值)。

protocol();

只能getter,返回當前url的協議(比如http,https)。

host();

只能getter,返回當前url的主機名。

port();

只能getter,返回當前url的端口號。

path([path]);

getter/setter, 返回當前url的子路徑(也就是當前url#后面的內容,不包括參數)。

search(search,[paramValue]);

getter/setter,返回當前url的參數的序列化json對象。

hash([hash]);

getter/setter,返回當前url的哈希值。

replace();

如果被調用,當前$digest過程中所有$location的變化將取代當前的歷史記錄,而不是增加新的歷史記錄。

state([state]);

返回當前url的歷史狀態對象(不包括任何參數)。

調用一個參數並且返回$location時改變歷史狀態對象。

事件

$locationChangeStart

在url將要被改變時廣播。可以使用preventDefault取消默認事件。

參數:

angularEvent:合成事件對象。

newUrl:新的url。

oldUrl:改變前的url。

newState:新的歷史狀態對象。

oldState:改變前的歷史狀態對象。

$locationChangeSuccess

在url成功的完成變化后廣播。

參數:

angularEvent:合成事件對象。

newUrl:新的url。

oldUrl:改變前的url。

newState:新的歷史狀態對象。

oldState:改變前的歷史狀態對象。

使用代碼:

  (function(){
     angular.module('Demo', [])
     .controller('testCtrl',["$location","$scope",testCtrl]);
     function testCtrl($location,$scope) {
        var url = "http://example.com:8080/#/some/path?foo=bar&baz=xoxo#hashValue";
        $location.absUrl();// http://example.com:8080/#/some/path?foo=bar&baz=xoxo#hashValue
        $location.url();// some/path?foo=bar&baz=xoxo
        $location.protocol();// http
        $location.host();// example.com
        $location.port();// 8080
        $location.path();// /some/path
        $location.search();// {foo: 'bar', baz: 'xoxo'}
        $location.search('foo', 'yipee');
        $location.search();// {foo: 'yipee', baz: 'xoxo'}
        $location.hash();// #hashValue
        $scope.$on("$locationChangeStart", function () {
          //監聽url變化,在變化前做想要的處理
        });
        $scope.$on("$locationChangeSuccess", function () {
          //監聽url變化,在變化后做想要的處理
        });
     }
  }());

$location在日常開發中是很有用的,特別是$locationChangeStart和$locationChangeSuccess,在做是否登錄判斷的時候配合攔截器使用,根據攔截器返回的狀態,監聽url變化並在需要登錄的時候退出到登錄頁面。

$window

一個瀏覽器窗口對象的引用。它是一個全局對象,在window中是全局可用的,但是它導致一些問題。在Angular中也經常通過$window服務提到它,因此它可以被重寫、刪除及測試。

$window 等同於 window。

驗證代碼:

  (function(){
     angular.module('Demo', [])
     .controller('testCtrl',["$window",testCtrl]);
     function testCtrl($window) {
         $window === window;
     }
  }());

$window對象可以用來獲取瀏覽器窗口各項屬性(如窗口高度寬度、瀏覽器版本等等)。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM