在 AngularJS 中,如何检测用户何时离开模板/页面? [英] In AngularJS, how to detect when user leaves template/page?
问题描述
我正在使用 Javascript 命令:setInterval.我喜欢在用户离开页面时停止它.
I am using the Javascript command: setInterval. I like to stop it when the user leaves the page.
此代码似乎运行良好:http://jsfiddle.net/PQz5k/
它检测用户何时离开页面.当用户单击链接转到不同的 HTML 页面或 URL,或者用户重新加载页面时,它会执行 Javascript 代码.
It detects when a user leaves a page. It executes Javascript code when a user clicks on a link to go to a different HTML page or URL, or if user reloads page.
但是,当我从一个 AngularJS 模板转到另一个模板时,它不起作用.例如,如果我在 template1.html,当用户离开 template1.html 转到 template2.html 时,我希望 Javascript 代码在 Controller1.js 中做一些事情.下面这段代码在 AngularJS 中的等价物是什么?:
However, it does not work when I go from one AngularJS template to another. As an example, if I am at template1.html, I want the Javascript code to do something in Controller1.js when the user leaves template1.html to go to template2.html. What is the equivalent of this code below in AngularJS?:
$(window).on('beforeunload', function() {
return 'Your own message goes here...';
});
推荐答案
我认为您有两个控制器,每个模板一个,如下所示:
I think you have two controllers, one for each template like this:
function Controller_1($scope...){
...
}
function Controller_2($scope...){
...
}
好吧,当你从一个模板切换到另一个模板时,会触发一个名为 $destroy 的事件,你可以在这里阅读它 http://docs.angularjs.org/api/ng.$rootScope.Scope#$destroy
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
假设我从带有 Controller_1 的模板切换到带有 Controller_2 的模板.Controller_1 有一个我想停止的时间间隔.您可以通过以下方式实现:
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);
});
}
这意味着当Controller_1的$scope被销毁时,事件将被调用并且间隔将被清除.
This will mean that when the $scope for Controller_1 is destroyed, the event will be called and the interval will be cleared.
这篇关于在 AngularJS 中,如何检测用户何时离开模板/页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!