Merott Merott - 3 months ago 95
AngularJS Question

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

With

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

Given the following code, if we directly load the URL
http://path/1/paramA/paramB
, 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?

Answer

The documentation reiterates your findings here: https://github.com/angular-ui/ui-router/wiki/URL-Routing#stateparams-service

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.

Comments