先展示下我的完整路徑:
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