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";   
    }
  }
})
Flip
  • 6,233
  • 7
  • 46
  • 75
Matt Bryson
  • 2,286
  • 2
  • 22
  • 42

3 Answers3

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 ... }
  }
})
henrikmerlander
  • 1,554
  • 13
  • 20
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

Community
  • 1
  • 1
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
  • 1
    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"; } }]}` – Matt Bryson Apr 06 '16 at 10:38
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");
Umair Farooq
  • 1,684
  • 2
  • 14
  • 25