Angular中通過$location獲取地址欄的參數詳解
Angular中通過$location獲取url中的參數
最近,項目開發正在進行時,心有點燥,許多東西沒來得及去研究,今天正想問題呢,同事問到如何獲取url中的參數,我一時半會還真沒想起來,剛剛特意研究了一下,常用的方法就以下幾種:
1.獲取當前完整的url路徑
var absurl = $location.absUrl(); //http://88:8100/#/homePage?id=10&a=100
2. 獲取當前url路徑(當前url#後面的內容,包括參數和哈希值)
var url = $location.url(); // /homePage?id=10&a=100
3. 獲取當前 url的子路徑(也就是當前url#後面的內容,不包括參數)
var pathUrl = $location.path() ///homePage
4.獲取當前url的協議(比如http,https)
var protocol = $location.protocol(); //http
5.獲取主機名
var localhost = $location.host(); //88
6.獲取當前url的端口
var port = $location.port(); //8100
7.獲取當前url的哈希值
var hash = $location.hash() //http://088
8.獲取當前url的參數的序列化json對象
var search = $location.search(); //{id: "10", a: "100"}
9. 獲取url參數
$location.search().name;
$location.search()[‘name‘];
10.註意問題
如果是這樣的地址:http://lele.sina.com?name=haha
需要在項目中註入$locationProvider服務
1 var searchApp = angular.module(‘searchApp‘, []); 2 3 searchApp.config([‘$locationProvider‘, function($locationProvider) { 4 5 $locationProvider.html5Mode(true); 6 7 }]); 8 9 searchApp.controller(‘MainCtrl‘, [‘$scope‘, ‘$location‘, function($scope, $location) { 10 11 if ($location.search().keyword) { 12 13 $scope.keyword = $location.search().keyword; 14 15 } 16 17 }]);
11.js中獲取地址欄參數的方法(附加)
url = https://www.baidu.com/s?ie=utf-8&f=3&rsv_bp=1&rsv_idx=2&tn=baiduhome_pg&wd=%E5%A8%83%E5%93%88%E5%93%88
console.log(window.location.href ); // "https://www.baidu.com/s?ie=utf-8&f=3&rsv_bp=1&rsv_idx=2&tn=baiduhome_pg&wd=%E5%A8%83%E5%93%88%E5%93%88"
console.log(window.location.host); // "www.baidu.com"
console.log(window.location.pathname); // "/s"
console.log(window.location.protocol); // "https:"
console.log(window.location.search); // "?ie=utf-8&f=3&rsv_bp=1&rsv_idx=2&tn=baiduhome_pg&wd=%E5%A8%83%E5%93%88%E5%93%88"
Angular中通過$location獲取地址欄的參數詳解