簡體   English   中英

控制器中的removeEventListener

[英]removeEventListener in controller

我有一個Angular應用程序使用angularJS v1.7和angular-ui-router。 在每個控制器中,我都有onkey事件,我在index.html中有一個模態菜單。 我的問題是當模態顯示我需要在控制器中刪除onkey事件並在模態中添加我的onkey事件。 我的應用程序中有很多控制器。

的index.html

<body ng-app="app-demo">

    <a ui-sref="home">Go to HOME</a>

    <ui-view></ui-view>

    <div ng-controller="vt" style="position: fixed; right: 0; top: 0;">
        <div>Modal show: {{ vt }}</div>
    </div>


    <script>
        app.controller('vt', function($scope,$rootScope) {
            $scope.vt = false;

            function onKeyupVT() {
                $scope.vt = !$scope.vt;
                $scope.$apply();
            }

            document.addEventListener('keyup',onKeyupVT);
        });
    </script>
</body>

home.html的

<div ng-controller="app-home">
    <h1>Home</h1>
    <button ng-click="goToSubPage()">Click me to view sub list.</button>
</div>

<div ui-view="list-1"></div>
<div ui-view="list-2"></div>

列表1.HTML

<div ng-controller="list-1">
    This is List - 1
</div>

homeController.js

app.controller('app-home', function($scope,$state) {

    $scope.goToSubPage = function() {
        $state.go('list-1');
    }

    function onKeyup() {
        console.log('Home');
    }

    document.addEventListener('keyup',onKeyup);
});
app.controller('list-1', function($scope,$stateParams) {
    function onKeyup() {
        console.log('list-1');
    }
    document.addEventListener('keyup',onKeyup);
});

我該怎么辦。 我是angularJS的新手。

一種方法是創建一個服務來委派keyup事件:

app.service("keyupDelegate", function() {
    this.target = new EventTarget();
    this.disableDispatch = false;

    document.addEventListener("keyup", keyupHandler);

    function keyupHandler(event) {
        if (!this.disableDispatch) {
            this.target.dispatchEvent(event);
        };
    }
});

然后每個視圖控制器都可以將其用作目標:

查看控制器

app.controller('app-home', function(keyupDelegate) {

    // ...    

    function onKeyup() {
        console.log('Home');
    }

    keyupDelegate.target.addEventListener('keyup',onKeyup);

    this.$onDestroy(function() {
        keyupDelegate.target.removeEventListener("keyup",onKeyup);
    });
});

模態控制器可以在激活時禁用調度:

模態控制器

app.controller("modal",function(keyupDelegate) {

    //...

    keyupDelegate.disableDispatch = true;

    this.$onDestroy(function() {
        keyupDelegate.disableDispatch = false;
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM