Merott Merott - 2 months ago 46
AngularJS Question

`ui-router` $stateParams vs. $state.params


, it's possible to inject either
into a controller to get access to parameters in the URL. However, accessing parameters through
only exposes parameters belonging to the state managed by the controller that accesses it, and its parent states, while
has all parameters, including those in any child states.

Given the following code, if we directly load the URL
, this is how it goes when the controllers load:

$stateProvider.state('a', {
url: 'path/:id/:anotherParam/',
controller: 'ACtrl',

$stateProvider.state('a.b', {
url: '/:yetAnotherParam',
controller: 'ABCtrl',

module.controller('ACtrl', function($stateParams, $state) {
$state.params; // has id, anotherParam, and yetAnotherParam
$stateParams; // has id and anotherParam

module.controller('ABCtrl', function($stateParams, $state) {
$state.params; // has id, anotherParam, and yetAnotherParam
$stateParams; // has id, anotherParam, and yetAnotherParam

The question is, why the difference? And are there best practices guidelines around when and why you should use, or avoid using either of them?


The documentation reiterates your findings here:

If my memory serves, $stateParams was introduced later than the original $state.params, and seems to be a simple helper injector to avoid continuously writing $state.params.

I doubt there are any best practice guidelines, but context wins out for me. If you simply want access to the params received into the url, then use $stateParams. If you want to know something more complex about the state itself, use $state.