Angular UI Router - 允许任何查询字符串参数 [英] Angular UI Router - allow ANY query string parameter

查看:17
本文介绍了Angular UI Router - 允许任何查询字符串参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Angular UI 路由器,这在大多数情况下都能很好地工作.但是,我遇到了提前不知道查询字符串参数名称的情况.

I am using the Angular UI Router and this works well in most situations. However, I have a situation where I don't know the names of the query string parameters ahead of time.

所以通常使用 UI 路由器你会定义一个这样的路由:

So normally with UI router you would define a route something like this:

$stateProvider.state('test', {
	url: '/test?testQueryStringParam',
	templateUrl: 'Test.html',
	controller: 'TestController'
});

然后在我的控制器中,我可以使用 $stateParams 访问 testQueryStringParam.

Then in my controller I can access the testQueryStringParam using $stateParams.

但是,使用 UI 路由器,您无法访问任何未在路由定义中指定的查询字符串参数.

However, with UI router you can't access any query string parameters not specified in the route definition.

Angular 框架附带的路由器确实允许您执行此操作.所以我尝试在我的 UI 路由器定义中使用 $location 服务.这确实有点工作.

The router that comes with the Angular framework, does allow you to do this. So I have tried using the $location service with my UI router defintion. This does sort of work.

当我想添加查询字符串参数时,我使用:

When I want to add a query string parameter I use:

$location.search("paramName", "paramValue");

当我想获取查询字符串值时,我只使用:

When I want to get the query string values I just use:

$location.search()

这会更新 URL,但不会重新实例化控制器(就像 $state.go($state.current, {}, {reload: true}) 那样).这似乎不是什么大问题,因为我可以自己重新加载数据.但是,如果您在浏览器中使用后退按钮,它会再次更改 URL,但不会重新实例化控制器.

This updates the URL, but doesn't re-instantiate the controller (like $state.go($state.current, {}, {reload: true}) would). This doesn't seem like a big problem because I can just re-load the data myself. However, if you use the back button in the browser, again it changes the URL, but doesn't re-instantiate the controller.

还有吗

  1. 我可以只使用 UI 路由器来让它工作吗?

  1. I can get this to work using just the UI Router?

获取使用 $location 实际重新实例化控制器的解决方法.?

Get the workaround of using $location to actually re-instantiate the controller.?

作为最后的手段,我也尝试过直接更新 window.location,但这会刷新整个页面,这是不可接受的.

As a last resort I also tried directing updating the window.location, but this refreshes the entire page which isn't acceptable.

谢谢

推荐答案

可以传递没有出现在URL中的非url参数

You can pass non url parameters that do not appear in URL

$stateProvider.state('test', {
    url: '/test?testQueryStringParam',
    params: {
    optParam: null,
    },
    templateUrl: 'Test.html',
    controller: 'TestController'
});

如你所见,optParam是一个可选参数,默认值为null,在URL中不可见

As you can see, optParam is an optional parameter with a default value of null and will not be visible in the URL

您可以使用 $stateParams

$stateParams.optParam

这是一个有用的博客

这篇关于Angular UI Router - 允许任何查询字符串参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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