How to send and retrieve parameters using $state.go toParams and $stateParams?

gwhn picture gwhn · Oct 22, 2013 · Viewed 225.7k times · Source

I am using AngularJS v1.2.0-rc.2 with ui-router v0.2.0. I want to pass the referrer state to another state so I use the toParams of $state.go like so:

$state.go('toState', {referer: $state.current.name});

According to the docs, this should populate the $stateParams on the toState controller, but it is undefined. What am I missing?

I've created a plunk to demonstrate:

http://plnkr.co/edit/ywEcG1

Answer

bbrown picture bbrown · May 29, 2014

If you want to pass non-URL state, then you must not use url when setting up your state. I found the answer on a PR and did some monkeying around to better understand.

$stateProvider.state('toState', {
  templateUrl:'wokka.html',
  controller:'stateController',
  params: {
    'referer': 'some default', 
    'param2': 'some default', 
    'etc': 'some default'
  }
});

Then you can navigate to it like so:

$state.go('toState', { 'referer':'jimbob', 'param2':37, 'etc':'bluebell' });

Or:

var result = { referer:'jimbob', param2:37, etc:'bluebell' };
$state.go('toState', result);

And in HTML thusly:

<a ui-sref="toState(thingy)" class="list-group-item" ng-repeat="thingy in thingies">{{ thingy.referer }}</a>

This use case is completely uncovered in the documentation, but I think it's a powerful means on transitioning state without using URLs.