Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
459 views
in Technique[技术] by (71.8m points)

javascript - Angular JS ui-router how to redirect to a child state from a parent?

When using onEnter to redirect to a state, if the new state is a child of the current state, an infinite loop occurs.

Example:

$stateProvider
  .state 'inventory',
    url: '/inventory'
    templateUrl: 'views/inventory.html'
    controller: 'InventoryCtrl'
    onEnter: () ->
      $state.go 'inventory.low'
  .state 'inventory.low',
    url: '/low'
    templateUrl: 'views/inventory-table.html'
    controller: 'LowInventoryCtrl'

When:

$state.go 'inventory.low'

Is called, the state inventory is re-initialized, causing it to be called again = infinite loop.

However, if the redirect state is:

$state.go 'otherStateThatIsNotAChild'

This issue does not occur. I assume that the parent state is being re-initialized, but why?

  1. Why is the parent state being reinitialized when .go is called on a child state?
  2. How then, would you handle redirecting to a child state?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

1) Why is the parent state being reinitialized when .go is called on a child state?

While a transition is in process, any $state.go/transitionTo will cause the currently in process transition to be Superseded. An in-process transition that is superseded is cancelled immediately. Since your original transition to inventory is not completed by the time all the states' onEnters are called, the original transition is cancelled and a new transition to inventory.low is started from the previously active state.

See ui-router src https://github.com/angular-ui/ui-router/blob/master/src/state.js#L897 ...

2) How then, would you handle redirecting to a child state?

You could...

  • Wrap $state.go in a $timeout() to allow the original transition to complete before redirecting.
  • Call $state.go from your controller instead. UI-router invokes the controller from the ui-view directive AFTER the transition is completed.

In any case, be very sure you want your app to redirect like this. If a user navigated directly to any other child state of inventory (such as inventory.high), the redirect will still occur, forcing them to inventory.low which would not be what they intended.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...