使用AngularJS路由持久化查询字符串 [英] Persisting query string with AngularJS routing
问题描述
我已经在大型Angular应用程序上工作了将近一年,而我一直坚持尝试做我认为微不足道的事情.
I've been working on a large Angular app for almost a year now and I'm stuck trying to do what I expected to be trivial.
这是我使用params的两条路线(为简洁起见,简称:)
Here are two routes I have with params (shortened for brevity):
/a/:id
/a/:id/b
假设用户位于/a/1
并修改了查询字符串,例如:
Let's say the user is at /a/1
and the query string is modified, for example:
/#/a/1?foo=123&bar=456
我想在页面上有一个链接,该链接将用户引导到第二条路线/a/1/b
,同时保持查询字符串,因此最终结果是重定向到:
I want to have a link on the page that directs the user to the second route /a/1/b
while maintaining the query string, so the end result is a redirection to:
/#/a/1/b?foo=123&bar=456
我正在使用Angular 1.2和新的ngRoute模块.
I am using Angular 1.2 and the new ngRoute module.
实现此行为的最佳方法是什么?
我应该提一下,我现在有一个可行的解决方案,这对我来说似乎很糟糕.该链接绑定到ng-click
处理程序,该处理程序实质上是以下内容:
I should mention I have a working solution right now that seems terrible to me. The link is bound to an ng-click
handler which is essentially the following:
$scope.navigateToBClick = function() {
var path = $location.path() + '/b',
search = $location.search();
$location.url(path + '?' + $.param(search));
};
推荐答案
我不确定您是否会认为这是比现有解决方案更好的解决方案,但这是一个解决方案.
I'm not sure if you would consider this a better solution than what you've got, but it is a solution.
在您的初始化代码中,添加以下内容:
In your initialization code, add the following:
app.run(["$rootScope", function ($rootScope) {
$rootScope.$on("$routeChangeSuccess", function (e, current) {
$rootScope.query = $.param(current.params);
});
}]);
然后,在您的HTML中,按如下所示进行链接:
Then, in your HTML, make your links as follows:
<a ng-href="#/a/{{id}}/b?{{query}}">Navigate to B</a>
这篇关于使用AngularJS路由持久化查询字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!