$location
是基于window.location
的服务;可以获取浏览器地址栏中的URL
,也可以修改浏览器地址栏的URL
。
一. 只能获取地址栏信息方法
以 http://www.my.com/app/index.html#/admin/member?x=y#hash
为例
1. absUrl()
$location.absUrl()
:获取完整URL
http://www.my.com/app/index.html#/admin/member?x=y#hash
2. protocol()
$location.protocol()
: 获取当前URL 协议;
http
3. host()
$location.host()
: 获取当前URL 主机名;
www.my.com
4. port()
$location.port()
: 获取当前URL 端口;
80
二. 获取和设置地址栏信息方法
1. url()
$location.url()
: 获取当前url路径(当前url#后面的内容,包括参数和哈希值);
/admin/member?x=y#hash
$location.url('/admin/role')
: 设置当前url,并定位到修改后的url;
定位到:http://www.my.com/app/index.html#/admin/role
2. hash()
$location.hash()
: 获取哈希值;
hash
$location.hash(‘hash1’)
: 设置哈希值;
url 设置为 http://www.my.com/app/index.html#/admin/member?x=y#hash1
3. path()
$location.path()
: 获取当前url的路径;不包括参数和hash值
/admin/member
$location.path(‘/admin/role’)
: 设置url路径,并定位到修改后的url;
url 设置为 http://www.my.com/app/index.html#/admin/role?x=y#hash1 并定位到该url
4. search()
$location.search()
: 获取当前url 的参数部分(对象形式);
{x: “y”}
$location.search({ a : "b" })
: 设置当前url的参数;
url 设置为 http://www.my.com/app/index.html#/admin/member?a=b#hash1
三. 替换URL 最后一条历史记录
$location.replace()
: 替换最后一条历史记录
注意:在浏览器地址变化的时候,它不会导致全页面刷新。要想在地址变化之后重载整个页面,请使用底层API $window.location.href = xxx
。