简体   繁体   English

在angular.js中动态添加和删除事件

[英]Dynamically add and remove events in angular.js

I'm new to angular.js and still struggling to catch best practices. 我是angular.js的新手,但仍在努力寻找最佳实践。 In this particular case I'm unsure what would be angular way to dynamically add and remove event handlers. 在这种情况下,我不确定动态添加和删除事件处理程序的方式。

I've created an simplified example that mimic my problem. 我创建了一个简化的示例来模仿我的问题。 In this example user can select from one of the items in a list. 在此示例中,用户可以从列表中的一项中进行选择。 To select an item, user clicks on button that will display list. 要选择一个项目,用户单击将显示列表的按钮。 Clicking on a list, selection will be changed and list hidden. 单击列表,将更改选择并隐藏列表。

But, what I want to do now is enable user to click anywhere on a page to hide list. 但是,我现在要做的是使用户可以单击页面上的任意位置以隐藏列表。 Using jQuery approach I would add click event handler on body or document that would change view state and hide popup list. 使用jQuery方法,我可以在bodydocument上添加click事件处理程序,以更改视图状态并隐藏弹出列表。

I've created an example on jsfiddle with this approach. 我使用这种方法在jsfiddle上创建了一个示例。 My question is: Is this good practice in angular.js? 我的问题是: angular.js中的这种好习惯吗? It feels kind of hackish. 感觉有点黑。

Also, please note that I don't want to have a event handler present on document all the time, only when list is displayed. 另外,请注意, 我不希望有出现在文档中的事件处理程序, 所有的时间,则显示列表,只有当。

Using practices described in angular.js guide , I've created directive that should handle the show/hide events. 使用angular.js guide中描述的实践,我创建了应该处理show / hide事件的指令。

.directive('toggleListDisplay', function($document) {
    return function(scope, element, attr) {
        var hideList = function (event) {
            scope.listDisplayed = false;
            $document.off('click', hideList);
            scope.$apply();
        };

        element.on('click', function(event) {
            event.stopPropagation();
            scope.listDisplayed = !scope.listDisplayed;
            if (scope.listDisplayed) {
                $document.on('click', hideList);
            } else {
                $document.off('click', hideList);
            }
            scope.$apply();
        });
    };
});

This directive will add click event handler on element, and will start looking for a click on a document untill list is displayed. 该指令将在元素上添加click事件处理程序,并将开始在文档上寻找单击,直到显示列表。 When it is not displayed anymore, it will stop watching for click event on document. 当不再显示时,它将停止监视文档上的click事件。

Working example can be found on jsfiddle . 工作示例可以在jsfiddle找到

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM