我已经使用$ on函数将我的监听器注册到$ broadcast事件
$scope.$on("onViewUpdated", this.callMe);
Run Code Online (Sandbox Code Playgroud)
我想根据特定的业务规则取消注册此侦听器.但我的问题是,一旦注册,我无法取消注册.
AngularJS中是否有任何方法可以取消注册特定的侦听器?像$ on这样取消注册此事件的方法可能是$ off.所以我可以说基于业务逻辑
$scope.$off("onViewUpdated", this.callMe);
Run Code Online (Sandbox Code Playgroud)
当有人播放"onViewUpdated"事件时,此函数停止被调用.
谢谢
编辑:我想从另一个函数取消注册监听器.不是我注册它的功能.
我正在使用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...';
});?
Run Code Online (Sandbox Code Playgroud) 我需要在用户关闭应用程序时执行一个函数,但需要考虑以下几点:
service,然后......onLocationChangeSuccess绑定也是无用的因此,此解决方案无法运行:https://stackoverflow.com/a/18355715/773595
因为这会在每次位置更改时触发,但是我需要的是当选项卡/窗口关闭时只有一个触发器.
我有一个简单的角度应用程序,有两个使用ngRoute加载的视图.当用户在视图之间导航以及用户离开页面时(刷新窗口,关闭选项卡或关闭浏览器),我需要在服务器上进行一些清理.
我的第一站就在这里:当用户离开页面时在angularjs中显示警报.它解决了用户在视图之间导航的第一种情况.我已经像这样处理了清理工作:
$scope.$on('$locationChangeStart', function (event) {
var answer = confirm("Are you sure you want to leave this page?")
if (answer) {
api.unlock($scope.id); //api is a service that I wrote. It uses angular $http service to handle communications and works in all other cases.
} else {
event.preventDefault();
}
});
Run Code Online (Sandbox Code Playgroud)
但是,我无法处理用户离开页面的情况.按照上述答案和此Google网上论坛帖子:https://groups.google.com/forum/#!topic / angular/-PfujIEdeCY我试过这个:
window.onbeforeunload = function (event) {
api.unlock($scope.id); //I don't necessarily need a confirmation dialogue, although that would be helpful.
};
Run Code Online (Sandbox Code Playgroud)
但它没有用.然后我在这里读到: 如何在onbeforeunload上执行ajax函数? …