关闭选项卡/浏览器时触发 Angularjs 事件 [英] Fire Angularjs event when tab/browser is closed
问题描述
我想在 Angularjs 控制器中触发 JS 代码.
I would like to fire JS code in Angularjs controller.
我有这个:
$scope.$on('$destroy', function () {
alert('page1');
});
当我离开使用该控制器的页面时,这工作正常,但在我关闭选项卡/浏览器时不起作用.
This is working fine when I'm navigating away from the page which is using that controller but its not working when I'm closing tab/browser.
当标签页/浏览器关闭时,我是否需要使用其他一些代码来触发 JS 代码?
Do I need to use some other code to fire JS code when tab/browser is closing?
推荐答案
来自 angular 文档:
From the angular docs:
$destroy();
从父作用域.删除意味着调用 $digest() 将不会更长的时间传播到当前作用域及其子作用域.删除也表示当前范围有资格进行垃圾回收.
Removes the current scope (and all of its children) from the parent scope. Removal implies that calls to $digest() will no longer propagate to the current scope and its children. Removal also implies that the current scope is eligible for garbage collection.
$destroy() 通常被 ngRepeat 等指令用于管理循环的展开.
The $destroy() is usually used by directives such as ngRepeat for managing the unrolling of the loop.
就在一个作用域被销毁之前,一个 $destroy 事件被广播这个范围.应用程序代码可以注册一个 $destroy 事件处理程序这将使它有机会执行任何必要的清理工作.
Just before a scope is destroyed, a $destroy event is broadcasted on this scope. Application code can register a $destroy event handler that will give it a chance to perform any necessary cleanup.
注意,在 AngularJS 中,还有一个 $destroy jQuery 事件,它可用于在删除元素之前清理 DOM 绑定DOM.
Note that, in AngularJS, there is also a $destroy jQuery event, which can be used to clean up DOM bindings before an element is removed from the DOM.
这只是处理作用域本身被销毁的情况,但在选项卡/浏览器关闭时似乎不会发生这种情况.
This just handles the situation where the scope itself is being destroyed, that does not seem to occur when the tab/browser is closed though.
您将不得不使用较低级别的方法 onunload 和 onbeforeunload 事件来处理这种情况,这是您可能会觉得有用的另一篇文章:
You will have to use lower level methods onunload and onbeforeunload events to handle this situation, here is another post you may find useful:
这篇关于关闭选项卡/浏览器时触发 Angularjs 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!