如何通过动态更改其键值参数来使用Angular $ location来设置我的新url位置?

时间:2013-07-05 14:19:41

标签: 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

我的模块接受查询对象来执行搜索:

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;
  });
}

这些方面正在通过网络表单中的本地模型传递:

 <input type="text" ng-model="query.location"/>
 <input type="text" ng-model="query.radius"/>
 <button type="button" ng-click="getSearch(query)">Search</button>

getResults函数的成功回调中,我试图将查询参数附加到URL,如上例所示:

$scope.getSearch = function(query){
  var search = $search.search(query);
  search.getResults(function(results){
    $scope.results = results;
    search.appendQueryToURL(query);
  });
}

如何在AngularJS中动态附加网址参数?

3 个答案:

答案 0 :(得分:39)

Using $location

$location.path('/newValue').search({key: value});

对于Non AngularJS应用程序:

您可以使用history.js将参数动态附加到网址。 然后拆分网址以检索参数并传递给angular:

History.replaceState({state:1}, "State 1", "?Param1=something");

我建议将history.js作为IE,直到ver9不支持历史对象推送状态,如果要使用IE10 +或谷歌浏览器,请使用历史状态对象更新网址。 希望它有所帮助:)

答案 1 :(得分:1)

对于上面的示例,$ location的path()将是

'/search' 

,根是

'http://example.com' 

回到他的问题,他没有要求用新路径更新位置,他要求动态更新新的键值对查询位置!

所以要做到这一点,它只是每天jQuery $ x(newX)!

$location.search({type: x, location: y, radius: z}); 

$location.search({type: x, location: y}); 

这都是jQuery !!

如果他想将搜索路径改为其他东西,他可以这样做:

$location.path('/otherPath'); 
//his new location would be 'example.com/otherPath' 

答案 2 :(得分:0)

实际上,不是使用$ 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>

并在getDataService()中执行

$http.get( serviceUrl, config ).success( ...

您的serviceUrl

example.com/search/Facility/Wayne,NJ/3/f

解析后(使用sprintf)