1

When the user hit F5 or refresh button I need to call a function before refreshing the page, I tried the below code and it did'nt work, please suggest me what I'm doing wrong and is there a better way to do this. I'm using Anuglar 1.5 with ui-router.

angular.module('module.name', [
]).controller('someController',['$scope', function($scope) {
    $scope.$on("$stateChangeStart", function () { 
        functionToCallOnPageRefresh();
    });
}]);

functionToCallOnPageRefresh() is not getting called on page refresh.

Amir Suhail
  • 1,284
  • 3
  • 12
  • 31
  • Do it when the page loads. – Will Apr 22 '16 at 04:31
  • But I don't want it to be called on first time of the page load, only when the page is about to refresh. – Amir Suhail Apr 22 '16 at 04:48
  • detect F5 key event in js http://stackoverflow.com/questions/14707602/capturing-f5-keypress-event-in-javascript-using-window-event-keycode-in-window-o – nisar Apr 22 '16 at 04:53
  • detect refresh but click $(window).unload(function() { alert('Handler for .unload() called.'); }); – nisar Apr 22 '16 at 04:53

1 Answers1

0

you need to create a parent state like as 'secure' and inherit every state in your application with that state like as-

angular.module('moduleName').config(['$stateProvider', '$urlRouterProvider',
    function ($stateProvider, $urlRouterProvider) {

        $stateProvider.
            state('secure', {
                url: "/",
                abstract: true,
                templateUrl: "/path/to your/ master page",
                resolve: {
                    factory: 'CheckRouting'
                }
            }).
            state('dashboard', {
                url: 'dashboard',
                templateUrl: 'path/to your /template',
                parent: 'secure',
               });

    }
]);

here i have mentioned

 resolve: {
                    factory: 'CheckRouting'
                }

in which CheckRouting inside resolve property, is a factory which is going to do some task (check user is login or not) on sate change or press f5.

in 'secure' state use 'resolve' property to execute a function if user press f5 or state change like as-

(function() {
    'use strict';

    angular.module('moduleName').factory('CheckRouting', ['$rootScope','$timeout' checkRouting]);

    function checkRouting($rootScope,$timeout) {

        if ( condition) { //user is loged in
            return true;
        } else {

                $timeout(function() {
                    $state.go('login');
                });

                return false;

        }
    }
}());