javascript 如何使用 AngularJS UI Router .go() 向 URL 添加搜索参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21923582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add search parameter to the URL using AngularJS UI Router .go()?
提问by kalisjoshua
Is there a way to add a search parameter to the URL when using UI-Router's $state.go()
? I would like to use a defined state with additional info in the URL instead of defining a new route with the same configuration.
有没有办法在使用 UI-Router 时向 URL 添加搜索参数$state.go()
?我想在 URL 中使用带有附加信息的定义状态,而不是定义具有相同配置的新路由。
I have a simple view defined:
我定义了一个简单的视图:
.when('page-with-form', {
template: 'views/page-with-form.html',
url: '/page-with-form'
})
I want the route to work as normal when someone navigates to /page-with-form
but when I have something else in the application that would redirect the user to that route with some additional information /page-with-form?error=true
something like this perhaps:
我希望当有人导航到该路线时,该路线可以正常工作,/page-with-form
但是当我在应用程序中有其他内容可以将用户重定向到该路线并带有一些附加信息时,/page-with-form?error=true
可能如下所示:
$state.go('page-with-form', '?error=true');
回答by Radim K?hler
This would be solution with ui-router
- working example
这将是解决方案ui-router
-工作示例
$stateProvider
.state('MyState', {
url: '/page-with-form?error',
templateUrl: 'view.page-with-form.html',
controller: 'MyCtrl',
})
The navigation to this state could be like this:
导航到这个状态可能是这样的:
// href
<a href="#/page-with-form">
<a href="#/page-with-form?error=true">
<a href="#/page-with-form?error=false">
//ui-sref
<a ui-sref="MyState({error:null})">
<a ui-sref="MyState({error:true})">
<a ui-sref="MyState({error:false})">
// state.go() - in fact very similar to ui-sref directive
$state.go('MyState', {error: null})
$state.go('MyState', {error: true})
$state.go('MyState', {error:false})
The documentation to url params:
url 参数的文档:
- Query Parameters(small cite)
- 查询参数(小引用)
You can also specify parameters as query parameters, following a '?':
您还可以将参数指定为查询参数,后跟“?”:
url: "/contacts?myParam"
// will match to url of "/contacts?myParam=value"
Test it in action here
在这里进行实际测试
回答by Khanh TO
As I understand, you're looking for optionalquery parameters. Fortunately, query parameters are optional by default. Just try: url: '/page-with-form?error'
据我了解,您正在寻找可选的查询参数。幸运的是,查询参数默认是可选的。你试一试:url: '/page-with-form?error'
.when('page-with-form', {
template: 'views/page-with-form.html',
url: '/page-with-form?error'
});
And use $state.go('page-with-form', {error:true});
并使用 $state.go('page-with-form', {error:true});