Coditty
5 years ago

How to pass custom data using $state.go() in ui-router




If you want to pass the data or custom parameters using $state.go() in Angular  to your controller or to resolve method,here is what you have to do.
So let's say we want to sent type of post when routing to editing state.
First, define state with param object:
$stateProvider
.state( 'edit', {
      url: '/code/:slug/edit',
      params: {
         params: null
       }
     //... 
})

Next, lets create state.go() redirection. This can be triggered when user click on edit content action  or it can be wrapped inside of function:
$state.go('edit',{slug:'slug-of-your-post-or-ID', params: {type: 'post'}});// or params: {type: 'page'}

And now back in stateProvider, we can use params.type by using $stateParams:
$stateProvider
.state( 'edit', {
      url: '/code/:slug/edit',
      params: {
         params: null
       }
     resolve:{
        resEditSnippet: ['$stateParams', function($stateParams){
 
              // check params.type value 
              if($stateParams.params.type=='post'){

               // do something

              }else{

               // do something else
                
              }
         
        }]
      }, 
})