当前位置:AngularJS API / ng / 服务(service) / $location

ng

$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 Object 合成事件对象。
newUrl string 新的url。
oldUrl string 改变前的url。
newState string 新的历史状态对象。
oldState string 改变前的历史状态对象。

$locationChangeSuccess

在url成功的完成变化后广播。

参数

参数 类型 描述
angularEvent Object 合成事件对象。
newUrl string 新的url。
oldUrl string 改变前的url。
newState string 新的历史状态对象。
oldState string 改变前的历史状态对象。

代码

(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变化,在变化后做想要的处理
        });
     }
  }());