[英]Getting URL variables via javascript
我有一個網址www.myurl.com/angularjs?var=myvar
我剛開始使用AngularJS(老實說就是javascript),試圖獲取'var'的值並將其傳遞給我的控制器,但我不知道如何訪問url變量
這是我的控制器...
vdApp.controller('ApplicantCtrl', ['$scope', '$http', function($scope, $http) {
$http.post('http://www.myurl.com/services', iWantToPassMyDataHere).success(function(data)
{
$scope.results = data;
});
}]);
我怎樣才能做到這一點?
謝謝
您應該為此使用$location
的search()
方法:
vdApp.controller('ApplicantCtrl', ['$scope', '$http', '$location', function($scope, $http, $location) {
$http.post('http://www.myurl.com/services', $location.search()).success(function(data) {
$scope.results = data;
});
}]);
document.location.search
從url返回查詢字符串
使用location.search
並按以下方式拆分查詢字符串:
var queryVals = location.search.split('&');
var v = queryVals[0].split('=')[1];
假設您的查詢參數var
是第一個參數。
如果不使用正則表達式,則會遇到#
問題。
var get = getUrlVars();
function getUrlVars() {
var vars = {};
/*Splits the variables into chuncks*/
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
/*Takes those chunks and removes anything after the hashtag*/
vars[key] = value.replace(/#\b[^#]*$/gi, '');
});
return vars;
}
這改變了
http://www.yourdomain.com/account/products/productEdit.php?product_key=2edc8450-e75b-11e4-97c1-d02788bb017c
至
get.product_key = '2edc8450-e75b-11e4-97c1-d02788bb017c'
和
http://www.yourdomain.com/account/products/productEdit.php?product_key=2edc8450-e75b-11e4-97c1-d02788bb017c#inventory
至
get.product_key = '2edc8450-e75b-11e4-97c1-d02788bb017c'
使用此網站來探索正則表達式。 http://regexr.com/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.