问题
Is there any way to get the parameters from parent state.
My states look like this.
$stateProvider
.state('home', {
url: '/home/:param1',
template: '<div>home<ui-view /></div>',
data: {
parentdata: 'parentdata'
}
})
.state('home.child', {
url: '/child/:param2',
template: '<div>index</div>',
data: {
childdata: 'childdata'
}
})
})
I want to access the data value of parent state from child state.
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
var tosateParam = toState.data.mycustomparam;
//If this is the child state, how can I access the parent state param
//may be like this toState.parent.data.parentParam
});
If my current state name is "ABC.childstate"
, how can I access the parameters from ABC
state.
回答1:
In case we need to access parent data {}
, we have to... profit from UI-Router
. See:
What Do Child States Inherit From Parent States?
small cite:
Child states DO inherit the following from parent states:
- Resolved dependencies via resolve
- Custom
data {}
properties
Nothing else is inherited (no controllers, templates, url, etc).
Having this clear doc message, we can have states like these (see working example here):
$stateProvider
.state('home', {
url: '/home/:param1',
data: { parentdata: 'parentdata', },
...
})
.state('home.child', {
url: '/child/:param2',
data: { childdata: 'childdata', },
...
})
And links like these:
<a href="#/home/justAParent">
<a href="#/home/first1/child/second1">
<a href="#/home/first2/child/second2">
Will as documentation says result (on a state change captured like this)
$rootScope.$on('$stateChangeStart',
function(event, toState , toParams, fromState, fromParams)
{
console.log(toState.data)
});
Into:
// href #/home/justAParent will show
Object {parentdata: "parentdata"}
// both #/home/first1/child/second1
// and #/home/first2/child/second2 will show
Object {parentdata: "parentdata", childdata: "childdata"}
Check it here
回答2:
There is a working plunker. Let's have these states
$stateProvider
.state('home', {
url: '/home/:param1',
template: '<div>home<ui-view /></div>',
})
.state('home.child', {
url: '/child/:param2',
template: '<div>index</div>',
})
And these links:
<a href="#/home/first1/child/second1">
<a href="#/home/first2/child/second2">
Then this:
$rootScope.$on('$stateChangeStart',
function(event, toState , toParams
, fromState, fromParams)
{
console.log(toParams)
});
Will give us this:
Object {param1: "first1", param2: "second1"}
Object {param1: "first2", param2: "second2"}
Check it here. Maybe also this could help a bit Angular ui-router - how to access parameters in nested, named view, passed from the parent template?
来源:https://stackoverflow.com/questions/26419801/acess-parameters-of-parent-state-from-child-state-in-statechangestart