gpt4 book ai didi

javascript - Angularjs - 如何从 URL 获取参数

转载 作者:行者123 更新时间:2023-11-28 13:26:36 25 4
gpt4 key购买 nike

我有一个这样的网址:http://myproject.com/apartments?location=123&arrival=01&departure=456&rooms=789

如何获取位置、到达、离开、房间的值并将其传递给我的服务。

我尝试使用 $location.search() 但无法获取值。结果:对象 { 位置=未定义,到达=未定义,出发=未定义,更多...}

我的服务:

angular.module('apartmentService', [])

.factory('Apartment', function ($http) {
return {
get: function (parameters) {

console.log(parameters);

return $http({
method: 'GET',
url: '/api/apartments',
params: {location: parameters}
});
}
};
});

我的 Controller :

angular.module('apartmentCtrl', [])

.controller('ApartmentController', function ($scope, $http, $location, Apartment) {
$scope.loading = true;

$scope.parameters = {
location: $location.search().location,
arrival: $location.search().arrival,
departure: $location.search().departure,
rooms: $location.search().rooms
};

Apartment.get($scope.parameters).success(function (data) {
$scope.apartments = data;
$scope.loading = false;
});
});

最佳答案

丑陋的不安全的两线:

paramsObject = {};
window.location.search.replace(/\?/,'').split('&').map(function(o){ paramsObject[o.split('=')[0]]= o.split('=')[1]});

paramsObject 将是:

Object {location: "123", arrival: "01", departure: "456", rooms: "789"} 

您可以将其直接注入(inject)到 $scope.parameters 中

plunker here

关于javascript - Angularjs - 如何从 URL 获取参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28722074/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com