I need to pass and recieve two parameters to the state I want to transit to using ui-sref
of ui-router.
Something like using the link below for transitioning the state to home
with foo
and bar
parameters:
<a ui-sref="home({foo: 'fooVal', bar: 'barVal'})">Go to home state with foo and bar parameters </a>
Receiving foo
and bar
values in a controller:
app.controller('SomeController', function($scope, $stateParam) {
//..
var foo = $stateParam.foo; //getting fooVal
var bar = $stateParam.bar; //getting barVal
//..
});
I get undefined
for $stateParam
in the controller.
Could somebody help me understand how to get it done?
Edit:
.state('home', {
url: '/',
views: {
'': {
templateUrl: 'home.html',
controller: 'MainRootCtrl'
},
'A@home': {
templateUrl: 'a.html',
controller: 'MainCtrl'
},
'B@home': {
templateUrl: 'b.html',
controller: 'SomeController'
}
}
});
I've created an example to show how to. Updated
state
definition would be:And this would be the controller:
What we can see is that the state home now has url defined as:
which means, that the params in url are expected as
These two links will correctly pass arguments into the controller:
Also, the controller does consume
$stateParams
instead of$stateParam
.Link to doc:
You can check it here
params : {}
There is also new, more granular setting
params : {}
. As we've already seen, we can declare parameters as part ofurl
. But withparams : {}
configuration - we can extend this definition or even introduce paramters which are not part of the url:Settings available for params are described in the documentation of the $stateProvider
Below is just an extract
We can call these params this way:
Check it in action here
You simply misspelled
$stateParam
, it should be$stateParams
(with an s). That's why you get undefined ;)You don't necessarily need to have the parameters inside the URL.
For instance, with:
You will be able to send parameters to the state, using either:
Of course, if you reload the page once on the
home
state, you will loose the state parameters, as they are not stored anywhere.A full description of this behavior is documented here, under the
params
row in thestate(name, stateConfig)
section.