每个控制器中的EventListener [英] EventListener in every controller

查看:69
本文介绍了每个控制器中的EventListener的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用Angular 1.7和ui-router的Angular应用程序.在我的index.html中,我有 document.addEventListener('keyup',onKeyupVT)-事件从不需要删除.在每个控制器中,我还具有onkeyup事件( document.addEventListener('keyup',onKeyup)).我在index.html中有一个按钮(不在控制器中).如果按钮切换,我将在控制器中添加或删除onkeyup事件(不在index.html中).

I have an Angular app use angular 1.7 and ui-router. In my index.html, I have document.addEventListener('keyup',onKeyupVT) - event never need remove. In every controller, I also have onkeyup Event (document.addEventListener('keyup',onKeyup)). I have a button in index.html (not in controller). If button toggle, I will add or remove onkeyup Event in controller (not in index.html).

我尝试在每个控制器中使用 $ rootScope.on('Event'+ n,function(e,data){//...})并调用 $ rootScope.emit('事件'+ n,数据).它可以工作,但是我需要在每个控制器中编写它.所以我该怎么做.谢谢您的帮助

I try $rootScope.on('Event' + n, function(e,data){ //... }) in every controller and call $rootScope.emit('Event' + n,data). It work but I need write it in every controller. So what Should I do. Thankyou for your help

推荐答案

如果控制器添加了文档范围的事件侦听器,则在销毁控制器时需要删除该侦听器.

If a controller adds a document wide event listener, it needs to remove the listener when the controller is destroyed.

app.controller("ctrl", function($document) {
    $document.on("keyup",onKeyup);
    function onKeyup(ev) {
        console.log(ev);
    }

    //REMOVE event listeners
    this.$onDestroy = function () {
        $document.off("keyup",onKeyup);
    };
})

这是需要的,以防止内存泄漏和其他意外行为.

This is needed to prevent memory leaks and other unintended behavior.

这篇关于每个控制器中的EventListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆