angularJS之$location服务
[ 2017/11/20, AngularJS , 3346阅, 0评 ]

The $location service parses the URL in the browser address bar (based on the window.location) and makes the URL available to your application. Changes to the URL in the address bar are reflected into $location service and changes to $location are reflected into the browser address bar.

The $location service:

  1. 1.Exposes the current URL in the browser address bar, so you can
    • Watch and observe the URL.
    • Change the URL.
  2. 2.Synchronizes the URL with the browser when the user
    • Changes the address bar.
    • Clicks the back or forward button (or clicks a History link).
    • Clicks on a link.
  3. 3.Represents the URL object as a set of methods (protocol, host, port, path, search, hash).

angularJS1.6.6官方文档之$location服务

常用操作(My Note)

使用$location.path('/home')或者$location.url('/home?id=123')做路由切换(即页面跳转)

使用$location.path('/home').replace()干掉历史记录(每次跳转时替换当前记录,达到不留历史记录的效果,以此屏蔽浏览器前进后退功能以及其他用户误操作等等)

angularJS1.6版本需要做以下配置,即去掉路由默认前缀符号(否则如果原来使用的低版本,更新后路由地址会出现"/"变"%2F","#"变"#!"的情况)

appModule.config(['$locationProvider', function($locationProvider) {
  $locationProvider.hashPrefix('');
}]);

代码中console一把,在控制台中便能看到$location所有的信息了

angularJS之$location.jpg

以下操作均以http://127.0.0.1/#/info/setting?id=10&a=100#a123为当前页面完整url(使用时不要忘记注入$location哦)

使用$location获取相关值($location的Methods)

//1.获取当前完整的url路径
$location.absUrl();
//结果:"http://127.0.0.1/#/info/setting?id=10&a=100#a123"

//2.获取当前url路径(当前url#后面的内容,包括参数和hash)
$location.url();//结果:"/info/setting?id=10&a=100#a123"

//3.获取当前url的子路径(也就是当前url#后面的内容,不包括参数)
$location.path();//结果:"/info/setting"

//4.获取当前url的参数的序列化json对象
$location.search();//结果:{id: "10", a: "100"}

//5.获取当前url的hash
$location.hash();//结果:"a123"

//6.获取当前url的协议(比如http,https)
$location.protocol();//结果:"http"

//7.获取当前url的端口
$location.port();//结果:80

//8.获取主机名
$location.host();//结果:"127.0.0.1"

//9.更多相关信息请访问文章末尾【相关资料】中的官方文档链接

使用$location修改或新增相应值

//1.修改url的子路径部分(也就是当前url#后面的所有内容)
$location.url('/home');//结果:"http://127.0.0.1/#/home"
$location.url('/home?a=123');//结果:"http://127.0.0.1/#/home?a=123"

//2.仅修改url#后面不包括参数的部分
$location.path('/home');//结果:"http://127.0.0.1/#/home?id=10&a=100#a123"

//3.修改url的hash部分
$location.hash('a456');//结果:"http://127.0.0.1/#/info/setting?id=10&a=100#a456"

//4.修改或增加url的参数部分(如果是已有属性名则修改,否则新增)
$location.search('id','66');//(key,value)
//结果:"http://127.0.0.1/#/info/setting?id=66&a=100#a123"
//此时$location.search()结果为:{id: "66", a: "100"}
$location.search('num','999');//(key,value)
//结果:"http://127.0.0.1/#/info/setting?id=10&a=100&num=999#a123"
//此时$location.search()结果为:{id: "10", a: "100", num: "999"}

//一次性修改或增加多个参数
$location.search({id:'22',a:'33',tid:123})//({key1:value1,key2:value2})

相关资料

angularJS1.6.6官方文档之$location服务

Angular 通过注入 $location 获取与修改当前页面URL

angularjs 1.6.0 (latest now) routes not working

feat($location): default hashPrefix to '!' #14202

有朋自远方来...评论一下呗O(∩_∩)O