UI路由器和查询参数 [英] UI Router and query parameters

查看:124
本文介绍了UI路由器和查询参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Angular,UI Router和Elasticsearch构建了一个小型搜索应用程序,并且试图在结果页面的url中获取UI Router查询参数.

I built a small search app using Angular, UI Router and Elasticsearch and I'm trying to get UI Router query parameters in the url on the results page.

我正在努力实现这一目标

I'm trying to achieve this

domain.com/search?user_search_terms

与此

.state('search', {
        url: '/search?q',

然后我在控制器中像这样初始化searchTerms和$ stateParams

and I init searchTerms and $stateParams like this in my controller

vm.searchTerms = $stateParams.q || '';

然后在我的控制器的搜索功能中就拥有了

and then in my search function in my controller I have this

 vm.search = function() {
          $state.go('search', {q: vm.searchTerms});
...

一切正常,直到我尝试实现UI Route查询参数.我仍然可以获得搜索建议,从一个州过渡到另一个州,但是搜索中断.

Everything works fine, until I try to implement the UI Route query parameters. I can still get search suggestions, transition from state to state but search breaks.

我以为我需要在config {}中实现Angular $ http get params,但是后来我意识到我只是想使用UI Router获取查询参数.看来我已经正确设置了UI路由器以获取查询参数,但是...我在做什么错了?

I thought I needed to implement Angular $http get params within a config {}, but then I realized I'm JUST trying to get query parameters using UI Router. It seems I have everything setup right with UI Router to get query parameters but ... what am I doing wrong?

推荐答案

对于查询参数,应使用 $state.params 而不是$stateParams

For query parameters, you should use $state.params instead of $stateParams

状态配置:

stateProvider.state({
    name: 'search',
    url: '/search?q',
    //...
}

控制者来自:

function fromCtrl ($state) {
    $state.go('search', {q: vm.searchTerms});
}

或模板/HTML链接来自:

<a ui-sref="search({q:'abc'})">my Link</a>

控制者:

function toCtrl ($state) {
    this.searchTerms = $state.params.q;
}


更新:将$transition$用于新版本> = 1.0.0( PLUNKER演示)
上面的代码对于两个版本都是相同的,只需要更改toCtrl ...


UPDATE: use $transition$ for new versions >= 1.0.0 (PLUNKER DEMO)
The code above is the same for both versions, only you need to change the toCtrl...

function toCtrl ($transition$) {
  this.myParam = $transition$.params().q;
}


如果您的searchTerms是一个对象,则可以使用JSON.stringify()JSON.parse()


如果您仍然有任何疑问,请查看以下帖子:
如何使用ui-router为AngularJS提取查询参数?
AngularJS:使用ui-router将对象传递到状态


If your searchTerms is an object, you can use JSON.stringify() and JSON.parse()


Check these posts if you still have any doubts:
How to extract query parameters with ui-router for AngularJS?
AngularJS: Pass an object into a state using ui-router

这篇关于UI路由器和查询参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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