在AngularJS,用户离开模板/页面时如何检测? [英] In AngularJS, how to detect when user leaves template/page?
问题描述
我使用的JavaScript命令:setInterval的。我想阻止它,当用户离开页面。
这code似乎运作良好: http://jsfiddle.net/PQz5k/
当用户离开网页它检测。它执行JavaScript code时的链接用户点击去一个不同的HTML页面或URL,或者如果用户重新加载页面。
然而,当我从一个AngularJS模板去到另一个它不工作。举个例子,如果我在template1.html,我想的JavaScript code做一下Controller1.js当用户离开template1.html去template2.html。在AngularJS这个code以下相当于是什么?
$(窗口)。在('beforeunload',函数(){
返回'你自己的信息放在这里......;
});
我觉得你有两个控制器,一个像这样每个模板:
函数Controller_1($范围...){
...
}
功能Controller_2($范围...){
...
}
那么,当你从一个模板切换到另一个有这么的燃煤名为$破坏事件,您可以在这里读了它的 http://docs.angularjs.org/api/ng.$rootScope.Scope#$destroy
比方说,我是从Controller_1模板与Controller_2模板切换。 Controller_1有我想停止的时间间隔。你可以做到这一点:
函数Controller_1($范围...){
VAR myInterval =的setInterval(...);
$范围。在$($消灭,函数(){
clearInterval(myInterval);
});
}
这将意味着,当Controller_1的$范围被破坏,该事件将被调用,时间间隔将被清除。
I am using the Javascript command: setInterval. I like to stop it when the user leaves the page.
This code seems to work well: http://jsfiddle.net/PQz5k/
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.
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...){
...
}
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...){
var myInterval = setInterval(...);
$scope.$on("$destroy", function(){
clearInterval(myInterval);
});
}
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屋!