Use Ui-Router's ui-sref Just to Set Query Para

2019-06-15 00:47发布

问题:

I have the following link.

<a ui-sref="...">Clicking this adds ?test=true to the query params.</a>

Is there a way to use the ui-sref attribute to just change query params without reloading the page or directing to another function?

回答1:

You should be able to do it by passing the arguments with the state.

try:-

<a ui-sref="yourStateName({test:true})">Clicking this adds ?test=true to the query params.</a>

Usage:

ui-sref='stateName' - Navigate to state, no params. 'stateName' can be any valid absolute or relative state, following the same syntax rules as $state.go()

ui-sref='stateName({param: value, param: value})' - Navigate to state, with params.



回答2:

In combination with PSL's answer, to prevent refreshing when setting up the state, just use the property reloadOnSearch: false.

.state('myState', {
      url: '/myState?test',
      reloadOnSearch : false,
      ...
    })

As long as your queries then take place within this same state.



回答3:

Just define the names of query params in the state url

$stateProvider.state('posts', {
    url: '/posts?test&answer',
    views: {
      content: {
        templateUrl: 'templates/posts/index',
        controller: 'PostsController'
      },
      navbar: {
        templateUrl: 'templates/partials/navbar'
      }
    }
  })

And use like this

<a ui-sref="posts({test: true, answer: false})">Next Page</a>

I am using ui-router version 0.2.15