Manage States between Routes in Angular

I use ui-router (https://github.com/angular-ui/ui-router) to route the url to state. For each state, we can specify the controller and the view. When transitioning from one state to another, we need to pass some data.

The way to specify a state is

$stateProvider.state('StateName', {
    url: 'request url',
    templateUrl: 'html file path'
})

There are a few ways to pass data to the state.

  1. Set the parameter in the url. For example, "contacts/{contactId}".  And use $stateParams to get the value. For example, $stateParams.contactId.
  2. In some cases, we don't want to specify parameters in url. Then we still can specify parameters in the state. e.g.
$stateProvider.state('StateName', {
    url: 'request url',
    params: {
       param1: null,
       param2: null
    },
    templateUrl: 'html file path'

Then you still can use $stateParams.param1 or $stateParams.param2 to get the values.
The way to set the parameter is:

$state.go('StateName', {param1: 'params Value'});

That's it. We can pass various parameters to the same url and the state should be able to handle it.

Facebooktwitterredditlinkedintumblr

Leave a comment

Your email address will not be published. Required fields are marked *