使用AngularJS路由持久化查询字符串 [英] Persisting query string with AngularJS routing

查看:68
本文介绍了使用AngularJS路由持久化查询字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在大型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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆