AngularJS [removed] in one controller is being triggered on another controller

后端 未结 4 1533
闹比i
闹比i 2021-02-01 18:16

Here is my problem, I have two views (View1 and View2) and a controller for each view (Ctrl1 and Ctrl2). In View1 I\'m trying to warn the user before he leaves the page accident

相关标签:
4条回答
  • 2021-02-01 18:50

    Unregister the onbeforeunload event when the controller which defined it goes out of scope:

    $scope.$on('$destroy', function() {
        delete window.onbeforeunload;
    });
    
    0 讨论(0)
  • 2021-02-01 19:00

    I just attempted the above solution, and that wasn't working for me. Even manually typing delete window.onbeforeunload in the console wouldn't remove the function. I needed to set the property to undefined instead.

    $scope.$on('$destroy', function(e){
      $window.onbeforeunload = undefined;
    });
    
    0 讨论(0)
  • 2021-02-01 19:06

    As an update to this, for anyone used angular-ui-router I'd now pass $transitions into your controller and use;

    $transitions.onStart({}, function ($transition)
    {
        $transition.abort();
        //return false;
    });
    
    0 讨论(0)
  • 2021-02-01 19:15

    For those of you using angular-ui-router you would use is $stateChangeStart instead of $locationChangeStart, e.g.

    $scope.$on('$stateChangeStart', function (event){
      if (forbit){
        event.preventDefault()
      }
      else{  
        return
      }
    })
    
    0 讨论(0)
提交回复
热议问题