In AngularJS, how to detect when user leaves template/page?

谁说我不能喝 提交于 2019-11-29 19:51:31

I think you have two controllers, one for each template like this:

function Controller_1($scope...){
    ...
}
function Controller_2($scope...){
    ...
}

Well, when you switch from one template to another there's an event that's fired called $destroy, you can read up on it here http://docs.angularjs.org/api/ng.$rootScope.Scope#$destroy

Let's say I'm switching from the template with Controller_1 to the template with Controller_2. Controller_1 has an interval I'd like to stop. You can accomplish this with:

function Controller_1($scope, $interval...){
    var myInterval = $interval(...);
    $scope.$on("$destroy", function(){
        $interval.cancel(myInterval);
    });
}

This will mean that when the $scope for Controller_1 is destroyed, the event will be called and the interval will be cleared.

This is for when you leave a template (also prompt a confirm dialog):

             function Controller_1($scope...){
               var myInterval = setInterval(...);
               $scope.$on('$locationChangeStart', function (event, next, current) {
                    console.log(current);

                    if (current.match("\/yourCurrentRoute")) {
                        var answer = confirm("Are you sure you want to leave this page?");
                        if (!answer) {
                            event.preventDefault();
                        }else{
                            clearInterval(myInterval);
                        }
                    }
                });
               }

if you are using ui-router then you can use the onExit, property

    $stateProvider.state('foo', {
        url: '/foo',        
        templateUrl: 'views/foo.html',    
        controller: 'fooController',
        onExit: ['$fooService', function($fooService) => {
            $fooService.hide();//do what u want to do here
        }]

    });

You can use a watcher to check when the location path is changed, something like this:

$scope.$watch(function(){
    return $location.path();
}, function(newPath, oldPath){
   //...Do something
})

Then, you can get the old location, and the new location and execute a function or whatever you want,

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!