简体   繁体   中英

Angular UI-Router: How to call child state without its parent?

We have recently move our application to Ui-Router from ng-route. And we are trying to refactor some points in our code regarding routing.

We have a list view and a detail view in our application. The detail view will be shown as a pop-up on top of the list view, so in order not to initialize all list controller logic again and again, we have defined our detail view as a child view-state. It looks like this:

  $stateProvider
    .state('list',
      {
        url: "/",
        template: '<list-directive></list-directive>'
      })
    .state('list.detail',
      {
        url: "/detail/{item_id}",
        template: '<detail-directive></detail-directive>'
      })

It actually works as expected. When i open a detail view from a list view, the list view (i mean the controller) does not run again, and when i close the detail view, the list view remains.

But now we would also like to call the detail view DIRECTLY, without revoking the parent . Currently when i directly call the detail state, the parent controller runs also.. How can i achieve this?

Is a parent - child relationship not a appropriate one for our scenario?

According ui-router doc :

Child states can be used to drill down from a more general feature to more specific one, or to implement a master/detail pattern. (...) The child state's view usually renders inside a viewport that the parent state created. This is referred to as Nested Views (...) These substates share the common parent state contacts and inherit data and behavior from the parent.

So I think you should use it if you don't want these behaviour .

It did work like this:

$stateProvider
    .state('list',
      {
        url: "/",
        template: '<list-directive></list-directive>'
      })
     .state('detail',
      {
        url: "/detail/{item_id}",
        template: '<detail-directive></detail-directive>'
      })
    .state('list.detail',
      {
        url: "detail/{item_id}",
        template: '<detail-directive></detail-directive>'
      })

But the angular is very fragile.. and behaves very different with very small changes.. the slashes are the problem.

Child state list.detail does not have a leading slash in its URL. But our new state detail (which has exctly the same content as the list.detail) should have a leading slash so it can be called directly. So We have the same state both as child and as parent.

Now when we call directly the URL "host/detail/5" we go to detail view without revoking the parent. And we we call ui-sref=".detail(5)" we go to child state (list.detail) within the parent

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM