programing

AngularJS에서 사용자가 템플릿 / 페이지를 떠날 때 감지하는 방법은 무엇입니까?

copysource 2021. 1. 16. 20:42
반응형

AngularJS에서 사용자가 템플릿 / 페이지를 떠날 때 감지하는 방법은 무엇입니까?


Javascript 명령 : setInterval을 사용하고 있습니다. 사용자가 페이지를 떠날 때 중지하고 싶습니다.

이 코드는 잘 작동하는 것 같습니다 : http://jsfiddle.net/PQz5k/

사용자가 페이지를 떠날 때이를 감지합니다. 사용자가 링크를 클릭하여 다른 HTML 페이지 또는 URL로 이동하거나 사용자가 페이지를 다시로드 할 때 Javascript 코드를 실행합니다.

그러나 한 AngularJS 템플릿에서 다른 템플릿으로 이동할 때 작동하지 않습니다. 예를 들어, 내가 template1.html에있는 경우 사용자가 template1.html을 떠나 template2.html로 이동할 때 Javascript 코드가 Controller1.js에서 작업을 수행하기를 원합니다. AngularJS에서 아래 코드와 동등한 것은 무엇입니까? :

$(window).on('beforeunload', function() {
    return 'Your own message goes here...';
});​

다음과 같이 각 템플릿에 하나씩 두 개의 컨트롤러가 있다고 생각합니다.

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

한 템플릿에서 다른 템플릿으로 전환 할 때 $ destroy라는 이벤트가 발생하면 여기에서 읽을 수 있습니다. http://docs.angularjs.org/api/ng.$rootScope.Scope#$destroy

Controller_1이있는 템플릿에서 Controller_2가있는 템플릿으로 전환한다고 가정 해 보겠습니다. Controller_1에 중지하고 싶은 간격이 있습니다. 다음을 사용하여이를 수행 할 수 있습니다.

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

이는 Controller_1에 대한 $ scope가 파괴되면 이벤트가 호출되고 간격이 지워짐을 의미합니다.


이는 템플릿을 떠날 때를위한 것입니다 (확인 대화 상자도 표시됨).

             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);
                        }
                    }
                });
               }

ui-router를 사용하는 경우 onExit, 속성을 사용할 수 있습니다.

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

    });

감시자를 사용하여 다음과 같이 위치 경로가 변경된시기를 확인할 수 있습니다.

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

그런 다음 이전 위치와 새 위치를 가져 와서 원하는 기능을 실행할 수 있습니다.

ReferenceURL : https://stackoverflow.com/questions/13885718/in-angularjs-how-to-detect-when-user-leaves-template-page

반응형