【Angular1】通过$location获取路径(参数) 并修改路径

先展示下我的完整路径:

http://localhost/#!/root/contract/businesscontract/edit%5B12%5D?id=3a6f61ca-508c-48d2-8a9a-cb4619568d73&page=1&taskContract=HADTASK&makeContract=HADMAKE

先打印出$location,如下图


获取URL相关内容:

//查看$location的内容
var all = $location;
console.log(all)
 
//1.获取当前完整的url路径  
var absUrl = $location.absUrl();
console.log(absUrl)
///输出内容:http://localhost/#!/root/contract/businesscontract/edit%5B12%5D?id=3a6f61ca-508c-48d2-8a9a-cb4619568d73&page=1&taskContract=HADTASK&makeContract=HADMAKE
 
//2.获取当前url的哈希值  
var hash = $location.hash()
console.log(hash)
//输出内容:''
 
//3.获取主机名  
var host = $location.host();
console.log(host)
//输出内容:localhost
 
//4. 获取当前url的子路径(也就是当前url#后面的内容,不包括参数)  
var path = $location.path()
console.log(path)
//输出内容:/root/contract/businesscontract/edit[12]
 
//5.获取当前url的端口  
var port = $location.port();
console.log(port)
//输出内容:80  
 
//6.获取当前url的协议
var protocol = $location.protocol();
console.log(protocol)
//输出内容:http
 
//7.获取当前url的参数的序列化json对象  
var search = $location.search();
console.log(search)
//输出内容:{id: "3a6f61ca-508c-48d2-8a9a-cb4619568d73", page: "1", taskContract: "HADTASK", makeContract: "HADMAKE"} 
 
//8. 获取当前url路径(当前url#后面的内容,包括参数和哈希值):  
var url = $location.url();
console.log(url)
//输出内容:/root/contract/businesscontract/edit%5B12%5D?id=3a6f61ca-508c-48d2-8a9a-cb4619568d73&page=1&taskContract=HADTASK&makeContract=HADMAKE


修改URL内容:

//1.修改url的子路径部分:  
$location.url('/testUrl');
console.log(url)
//输出内容:http://localhost/#!/testUrl 
 
//2.修改url的参数部分
//第一个参数表示url参数的属性名
$location.search('id', '123')
// 结果:http://localhost/#!/root/contract/businesscontract/edit%5B12%5D?id=123&page=1&taskContract=HADTASK&makeContract=HADMAKE
 
//第二个参数是该属性名的属性值,如果是已有属性名,则修改,如果不是已有属性,则新增
$location.search('name', 'test')
// 结果: http://localhost/#!/root/contract/businesscontract/edit%5B12%5D?id=123&page=1&taskContract=HADTASK&makeContract=HADMAKE&name=test
 
//3.一次性修改多个参数  
$location.search({
    id: '666',
    taskContract: 'abc'
})
//结果:http://localhost/#!/root/contract/businesscontract/edit%5B12%5D?id=666&taskContract=abc
 
//4.第一个值表示url参数的属性名,如果是已有属性名,则删除该属性,如果不是已有属性,那就等于没改过  
$location.search('id', null)
//结果:http://localhost/#!/root/contract/businesscontract/edit%5B12%5D?page=1&taskContract=HADTASK&makeContract=HADMAKE
 
//5.修改url的哈希值部分  
$location.hash('testhash');
//目前我的页面测试路径找不到报错了
 
//6.修改替换url的哈希值部分  
$location.path('/testreplace').replace()
//结果:http://localhost/#!/testreplace?taskContract=abc#testhash

--------------------- 
原文:https://blog.csdn.net/a_small_insect/article/details/79479653 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章