Use optional parameters in $state.go

Issue

I have a website by AngularJS and ui-router. I have defined 2 states as follows:

.state('home', {
       url: '/home/{id}',
       ...
})
.state('edit', {
       url: '/edit/{id}?connected&ifIni&redirectToRun',
       ...

In a controller, I could use $state.go('home', { id: id }) to navigate to the home page.

My question is if I could use e.g., $state.go('edit', { id: id, connected: connected, ifIni: ifIni, redirectToRun: redirectToRun }) to navigate to the edit page.

Solution

You can do that in two differnet ways, one is by adding params in routeConfiguration and other is to add as query parameters to URL

Adding Params:

Route Configuration:

$stateProvider.state('edit', {
  templateUrl:'edit.html',
  controller:'editController',
  params: {
    'id': ''
    'referer': '', 
    'connected': '', 
    'ifIni': '',
    'redirectToRun': ''
  }
});

Redirection:

$state.go('edit', { id: id, connected: connected, ifIni: ifIni, redirectToRun: redirectToRun })

If you want to use Query params:

Route Configuration:

$stateProvider.state('edit', {
  url: '/edit/{id}?connected&ifIni&redirectToRun',
  templateUrl:'edit.html',
  controller:'editController'
});

Redirection:

$state.go('edit', { id: id, connected: connected, ifIni: ifIni, redirectToRun: redirectToRun })

Here is the Documentation

Answered By – Sravan

Answer Checked By – Katrina (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.