angular-ui / ui-router

The de-facto solution to flexible routing with nested views in AngularJS
http://ui-router.github.io/
MIT License
13.56k stars 3.01k forks source link

Transition Hook Firing Multiple Times #3644

Closed MNguyen1515 closed 6 years ago

MNguyen1515 commented 6 years ago

This issue tracker is for Bug Reports and Feature Requests only.

Please direct requests for help to StackOverflow. See http://bit.ly/UIR-SOF for details.

This is a (check one box):

My version of UI-Router is: (1.0.3)

Bug Report

Current Behavior:

A Transition Hook is being executed multiple times. Plunker example showcasing this provided.

Expected Behavior:

Transition Hook should only execute once. Should be similar to what's to what's on this Plunker: https://plnkr.co/edit/c6ySScGZFhInrhuj0SFK?p=preview Open up the devtools console and click between Hello and About.

Link to Plunker or stackblitz that reproduces the issue:

https://plnkr.co/edit/YaVCJfGEtPOS5JNSLElR?p=preview

Instructions:

  1. Open up dev tools
  2. Go to console
  3. Click between the Hello and About links several times
  4. Look at console logs. Parts will be repeat N times, where N is the number of times the 'Hello' link has been clicked.

Other Notes

Not sure if my implementation is incorrect. Differences between two Plunkers:

  1. Multiple controllers in the one with issues
  2. Controller is provided to the state

Thanks

OlofFredriksson commented 6 years ago

Hello! I'm pretty sure you need to deregister the transitions once the controller is destroyed to avoid this problem.

var deregisterFn = $transitions.onBefore(...)

$onDestroy() {
  deregisterFn()
}

Source: https://github.com/angular-ui/ui-router/issues/2930#issuecomment-241087223

christopherthielen commented 6 years ago

@OlofFredriksson is correct, you need to clean up hooks that are registered inside a controller.

Here is a forked plunker that demonstrates the difference: https://plnkr.co/edit/iEGFqh8DEpJhMA31sni4?p=preview