Jacob
Jacob

Reputation: 1896

How do I configure this views properly with ui-router in AngularJS?

I'm trying to modify an existing AngularJS application that uses ui-router. The routing table is pretty big and even though I can make it work, I don't understand why.

The states are configured using "Object-based" states, and they look like:

parent = {
    abstract: true,
    name: 'parent',
    views: {
        'key': {
            templateUrl: '/app/views/parent.html'
        }
    }
},
child = {
    name: 'parent.child',
    views: {
        'other-key': {
            templateUrl: '/app/views/child.html'
        }
    }
},

The dot syntax is used to infer the hierarchy. Regarding the views, parent.html contains some html and a reference to child.html like:

<div data-ui-view="other-key"></div>

And, it works!. As far as I understand, when child is activated, the parent and abstract state (that can't be activated) is used to inherit the data. That makes me think that I should be able to put these two views in the same state, and they should work.

However, I have two scenarios:

Seems reasonable to think that everything should work exactly in the same way if they are inside, together, of the views collection of the same state:

child = {
    name: 'parent.child',
    views: {
        'key': {
            templateUrl: '/app/views/parent.html'
        }
        'other-key': {
            templateUrl: '/app/views/child.html'
        }
    }
},

When the state is activated all the information is available to compute the state, but somehow it does not work.

Hope I'm including all the information. The routing table is too big to be pasted here.

Upvotes: 1

Views: 59

Answers (1)

thomaux
thomaux

Reputation: 19718

The issues with both scenarios are slightly different, so I'll tackle them separately.

Moving everything up to the parent state

In this case, you can't render the child template because it is inside the parent view. Hence, when ui-router's resolving your state it can only locate one named view (the parent) and thus it's the only one that will be rendered.

Moving everything down to the child state

The issue here is pretty much the same as in the first case, however nothing is getting rendered now because the child state can't locate the parent state. You could fix this by absolutely referencing the parent's named view:

'key@parent': '/app/views/parent.html'

I'm not entirely sure, but my guess is this still won't suffice to render both views (I believe only the parent will be rendered and hence you'll end up in exactly the same situation as if you would have moved both to the parent).

The solution

Pretty straight forward, put both named views on the same level and it will work or keep them in separate states to allow the child state to resolve its named view from the parent's template.

Upvotes: 1

Related Questions