AngularJS - Detecting, stalling, and cancelling route changes

后端 未结 3 1355
忘掉有多难
忘掉有多难 2020-12-29 14:57

I can see the event $routeChangeStart in my controller, but I don\'t see how to tell Angular to stay. I need to popup something like \"Do you want to SAVE, DELE

相关标签:
3条回答
  • 2020-12-29 15:08

    The documented way of doing this is to use the resolve property of the routes.

    The '$route' service documentation says that a '$routeChangeError' event is fired if any of the 'resolve' promises are rejected.1 That means you can use the '$routeProvider' to specify a function which returns a promise that later gets rejected if you would like to prevent the route from changing.

    One advantage of this method is that the promise can be resolved or rejected based on the results of asynchronous tasks.

    0 讨论(0)
  • 2020-12-29 15:18

    You are listening to the wrong event, I did a bit of googling but couldn't find anything in the docs. A quick test of this:

    $scope.$on("$locationChangeStart", function(event){
        event.preventDefault();
    })
    

    In a global controller prevented the location from changing.

    0 讨论(0)
  • 2020-12-29 15:22
    $scope.$watch("$locationChangeStart", function(event){
        event.preventDefault(); 
    });
    

    You can do like this as well. Benefit of doing this way is that it doesn't trigger through if() statement with $on ...as you well see that below code will trigger no matter what the condition is:

    if(condition){ //it doesn't matter what the condition is true or false
      $scope.$on("$locationChangeStart", function(event){ //this gets triggered
         event.preventDefault();  
      }); 
    }
    
    0 讨论(0)
提交回复
热议问题