Angular-ui-router child state with multiple parent

2019-07-08 19:42发布

问题:

Using Angular-ui-router, is there a possibility to define a child-state that has multiple parent states:

$stateProvider
    .state("parent1", {
        url: '/',
        templateUrl: 'parent1.html'
    })
    .state('parent2', {
        url: '/parent2',
        templateUrl: 'parent2.html'
    })

    //Make accessible from every state parent-state
    .state("child", {
        url: 'child',
//TODO  parents: ['parent1', 'parent2']
        onEnter: function() {
            //do something;
        }
    })

Example:

Your Angular app has a directive that is used multiple times in different states in your app. The directive itself includes a link which redirects to a different state. Depending on where the directive is used, it should append its child-state to the current active parent-state.

It just doesn't seem right to define states for each permutation like state1.child, state2.child etc.. There needs to be a better way.

回答1:

This kind of hierarchy would go against the DOM tree structure, which by definition doesn't allow multiple parents of same element.

Moreover, it is error (and headache) prone and could easily result in the multiple inheritance diamond problem, as child state do inherit from parent state in some cases.

It sounds like a directive, and not a state, would be the better solution for what you're looking for.

EDIT:

Just saw that there's a closed issue on this, which is closed because he reached the same conclusion (that a directive is the better way)