Can onbeforeunload event be watch by $watch in angular js?

235 Views Asked by At

I am a newbie of angularjs and now I am stack on catching event of onbeforeunload event. I would like to show to some response to user when they leave the page. And I would like to watch onbeforeunload event by $watch and execute my message display function.

But how can I watch that event? Could anybody please answer me? Thank you very much.

1

There are 1 best solutions below

0
On BEST ANSWER

How about this:

$scope.$on('$locationChangeStart', function( event ) {
    var answer = confirm("Your message....");
    if (!answer) {
        event.preventDefault();
    }
});

With $watch which I think you don't need it in here. Something like this:

$scope.$watch(function(){
        return $location.path();
}, function(newPath, oldPath){
   // Compare it, and trigger your message function.
})