angularjsangular-ui-routerangular-ui-router-extras

Query Param value is not updated in angularjs router?


I have defined my state with one constant param(page), one dynamic param(id), one query param(date) like this.

   $stateProvider.state('test', {
   url: '/page/:id?date',
   controller: 'MyCtrl'       
 });

I am calling this state from my controller with passing query param like this

$state.go("test", {id: '5',date:'06/09/2016'});

After called this state I am getting params,

console.log($stateParams.id) -> '5';
console.log($stateParams.date) -> '06/09/2016'(as expected results)

Again I am calling the same state from my controller without passing query param like this.

$state.go("test", {id: '7'});

Now I am getting the below stateparams

console.log($stateParams.id) -> '7';(expected)
console.log($stateParams.date) -> '06/09/2016';(which shouldn't be right here.)

$stateParams.date should be undefined because I didn't pass it while calling the state. But In the Url by default It was passing, once I was passed it. As It was optional param so it should be neglected while not passing. How to make it 'Undefined' while calling the same state again without passing the param? I know If I passed $stateParams.date=null or someother name It will reflected. But I dont need to pass via my router url? Is there any other way to achieve this?

UPDATE 1: After the posted answer I used '{inherit:false}' as the expected results. But It didn't inherit any of the param values which I wasn't passed while calling the state. But I don't want to inherit only optional param values. See the below code.

  $stateProvider.state('test', {
   url: '/page/:id/:type?date',
   controller: 'MyCtrl'       
 });

Here I am having to dynamic param id and type. If suppose I called with updated value of id only then type is not inherited. But I want to inherit type param value not the date (conditional Param) value.

$state.go("test", {id: '3'},{inherit:false});

console.log($stateParams.type) -> undefined.(here I want the 'type' param value should be inherited without passing. becaz I don't want update the value of 'type'. I just want the previous value should be maintain. Anyway to achieve this?


Solution

  • Add another argument to the function call; {inherit:false} tells $state.go() not to inherit previous values.

    $state.go("test", {id: '7'}, {inherit: false});
    

    The default for inherit is true, as described in the docs here.