Search code examples
angularjsangular-ui-routerangular-ui

How to define defaults for query params in AngularJS UI-Router?


I have a route:

.state('list', {
  url:'/list?query',
  templateUrl: '/views/list.html',
  controller: 'ListCtrl as vm'
})

Is there a way to ensure a default value for the query?

I don't want to do it in the controller, as I use the same controller for other routes, and the controller has certain behaviour if the query is undefined.

What I want is this particular route to default that query.

In the old angular route I have done this sort of thing...

.when('/list', 
  templateUrl: '/views/list.html',
  controller: 'ListCtrl'
  controllerAs:true,
  redirectTo:function(routeParams, path, search) {
    if(!search.query) {
      return "list?query=defaultSearch";   
    }
  }
})

Solution

  • We can use a setting called params. There is a working plunker

    .state('list', {
      url:'/list?query',
      templateUrl: 'views/list.html',
      controller: 'ListCtrl as vm',
      params: { query: 'DEFAULT VALUE' }, // here the default
    })
    

    and these links will work as expected

    <a href="#/list?"> - with default 'query' value 
    <a href="#/list?query=someParam">
    <a ui-sref="list({query:'theParam'})">
    

    Check it in action here

    The details are discussed here:

    Angular ui router passing data between states without URL