2

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

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

awesome, this looks like the perfect answer. To date I've been doing this, which is a bit hacky.... resolve: {updateParams: ['$stateParams', function($stateParams){ if(!$stateParams.query) { $stateParams.query="DEFAULT VALUE"; } }]}
2

You could use the onEnter method to execute logic before your controller loads.

From the ui-router wiki https://github.com/angular-ui/ui-router/wiki:

$stateProvider.state("contacts", {
  template: '<h1>{{title}}</h1>',
  resolve: { title: 'My Contacts' },
  controller: function($scope, title){
    $scope.title = title;
  },
  onEnter: function($location){
    if($location){ ... do something ... }
  }
})

Comments

0

If I am getting you right, you need to go to a state if the user requested state does not match any of the states defined.

If this is the requirement, then try using "otherwise" method of $urlRouterProvider

like,

$urlRouterProvider.otherwise("/default-state");

1 Comment

I tried this, but it appears that query params are optional, so the route matches if it defined or not.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.