1

controller:

app.run(function ($rootScope, $templateCache) {
    $rootScope.$on('$viewContentLoaded', function ($scope, $http) {     
        $templateCache.removeAll();
        alert("refresh.....");
        $http({
            url: '/angularjs-restful/check/check-session',
            method: "POST",
            data: {},
            isArray: false
        }).success(function(data, status, headers, config){
            alert("success.....");
            console.log('status: ' + status);
            console.log('data: ' + data);
        }).error(function(data, status, headers, config){
            alert('error');
        });        
        alert("end.....");
    });       
});

I need to make an AJAX call when a user hit f5 on keyboard or manually refresh the page with a mouse. How can I achieve this? the url is a rest service that either return true or false.

onelazyguy
  • 41
  • 2
  • 9

1 Answers1

0

you can use window.onbeforeunload function to listen to the unload event which should fire on f5.

function ctrl($scope, $window) {
    angular.element($window).bind('beforeunload', function() {
        console.log('do ajax call');
    });
}
Jayantha Lal Sirisena
  • 21,216
  • 11
  • 71
  • 92
  • I would instead recommend binding to the `beforeunload` event using the `$window` service in case you need to test your AJAX call through mocks. Example: http://jsfiddle.net/LkPJX/ – miqh Mar 21 '14 at 03:40
  • I tried and still does not work. How do I add your code onto the code that I posted above? When I refresh the page, the alert("refresh.....") is working fine and after the alert, I need to make an ajax call using $http to call a service...I added the code that you provided "angular.element($window).bind('beforeunload', function() { console.log('do ajax call'); });" but it does not run after alert has finished – onelazyguy Mar 21 '14 at 14:20
  • If testing on IE [you'll need to also call `$rootScope.$digest()`](http://stackoverflow.com/a/38251551/1108708). – Jason Rust Jul 07 '16 at 17:20