Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UI Router and query parameters

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

with this

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

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});
...

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.

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?

like image 455
user3125823 Avatar asked Feb 15 '17 19:02

user3125823


1 Answers

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

STATE CONFIG:

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

CONTROLLER FROM:

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

OR TEMPLATE/HTML LINK FROM:

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

CONTROLLER TO:

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


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;
}

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

like image 165
The.Bear Avatar answered Nov 06 '22 12:11

The.Bear