Rahul Gupta Rahul Gupta - 4 months ago 46
AngularJS Question

Override the parent url with child url in UI-router (Angular)

This is the configuration i'm using for my ui-router:

.state('parent', {
url: '/child1'
controller: ParentController,
abstract: true
})

.state('parent.child1', {
url: ''
})

.state('parent.child2', {
url: '/child2'
})


What I want to acheive ?



I want a /child1 url that I wanted to be default so I made the parent as abstract with child state url as 'empty'.

So I want that when user visits child2 state, the parent url gets replaced rather than appending it. How can i achieve that ?

Answer

If I understand you right, (please correct me if I'm wrong) you are looking to setup a routing service to achieve the following routes:

/, /child1 and /child2 and you want all states to be bound with ParentController

If that is correct you can achieve this with the following:

.state('parent', {
  url: '/',
  controller: ParentController,
})

.state('parent.child1', {
  url: '^/child1'
})

.state('parent.child2', {
  url: '^/child2'
})

For example if we were running https://localhost:3000 we could navigate as such:

parent or / would give us https://localhost:3000/

parent.child1 or /child1 would give us https://localhost:3000/child1

parent.child2 or /child2 would give us https://localhost:3000/child2

The ParentController would be invoked by all states.

Comments