Javascript 如何使用Angular$location动态更改其键值参数来设置我的新url位置?
假设我有一个RESTful端点,它接受一系列方面来查询数据。这里有几个例子:Javascript 如何使用Angular$location动态更改其键值参数来设置我的新url位置?,javascript,angularjs,Javascript,Angularjs,假设我有一个RESTful端点,它接受一系列方面来查询数据。这里有几个例子: example.com/search?type=Doctor&location=Boston,MA&radius=2 example.com/search?type=Facility&location=Wayne,NJ&radius=3&gender=f example.com/search?type=Doctor&location=Patterson,NJ 我
example.com/search?type=Doctor&location=Boston,MA&radius=2
example.com/search?type=Facility&location=Wayne,NJ&radius=3&gender=f
example.com/search?type=Doctor&location=Patterson,NJ
我的模块接受查询对象以执行搜索:
console.log(query);
{
type:'Doctor',
location:'Boston,MA',
radius:'2'
}
$scope.getSearch = function(query){
var search = $search.search(query);
search.getResults(function(results){
$scope.results = results;
});
}
这些方面以web形式通过本地模型传递:
<input type="text" ng-model="query.location"/>
<input type="text" ng-model="query.radius"/>
<button type="button" ng-click="getSearch(query)">Search</button>
如何在AngularJS中动态附加URL参数?
对于非AngularJS应用程序:
可以使用history.js将参数动态附加到url。
然后拆分url以检索参数并传递给angular:
History.replaceState({state:1}, "State 1", "?Param1=something");
我建议将history.js作为IE,直到ver9不支持历史对象推送状态,如果您要使用IE10+或google chrome,请使用历史状态对象更新url。
希望有帮助:)对于上面的示例,$位置的路径()将是
'/search'
根是
'http://example.com'
回到他的问题,他没有要求用新路径更新位置,而是要求用新的键值对动态查询更新位置
所以要做到这一点,只需每天jQuery$x(newX)
或
都是jQuery
如果他想将搜索路径更改为其他路径,他可以执行以下操作:
$location.path('/otherPath');
//his new location would be 'example.com/otherPath'
事实上,与其使用$location调用您的数据服务端点,通常的方法是
<form id='searchForm' ng-submit="getDataService()" ng-controller="aController">
<input ng-model="type"/>
<input ng-model="location"/>
<input ng-model="radius"/>
<input ng-model="gender"/>
<button type='submit'/>
</form>
您的serviceUrl为
example.com/search/Facility/Wayne,NJ/3/f
解析后(使用sprintf)真的没有本地AngularJS方法可以为您完成这项工作吗?我的回答反映了这一点。请投票,如果这是你正在寻找的没有使用它很多,但请遵循这一点,这可能会给你一个更好的想法:一个很好的界面触摸网址;我有点失望,因为它需要一个散列(可能只有当url以
/
结尾时才需要),但是你能做什么呢?以这种方式链接路径和搜索将导致现有参数被替换。op的问题是附加。因此,请使用$location.search(key,paramValue)附加参数,然后调用$location.path(yourPath)。是否查找$location.search()?@KhanhTO-Holy。。。对它甚至接受键值对。
$location.search({type: x, location: y});
$location.path('/otherPath');
//his new location would be 'example.com/otherPath'
<form id='searchForm' ng-submit="getDataService()" ng-controller="aController">
<input ng-model="type"/>
<input ng-model="location"/>
<input ng-model="radius"/>
<input ng-model="gender"/>
<button type='submit'/>
</form>
$http.get( serviceUrl, config ).success( ...
example.com/search/Facility/Wayne,NJ/3/f