简体   繁体   English

如何从指令内部处理点击事件?

[英]How to handle click events from inside of the directive?

I have a modal component that takes an object with binding (ng-model).我有一个模态组件,它带有一个带有绑定的对象(ng-model)。 Something like:就像是:

<modal ng-model="modals.createContact"></modal>

I'm checking for $ctrl.ngModel.show to show/hide the modal:我正在检查$ctrl.ngModel.show以显示/隐藏模式:

<div class="modal" ng-show="$ctrl.ngModel.show" ng-transclude></div>

I show/hide modal by setting modals.createContact.show using ng-click directive:我通过使用ng-click指令设置modals.createContact.show来显示/隐藏模态:

<button ng-click="modals.createContact.show = true"></button>

But this solution is hard to maintain.但是这个解决方案很难维护。

I need a directive something like this to toggle modal's show property:我需要一个类似这样的指令来切换模态的show属性:

<button modal="modals.createContact">Toggle modal</button>

Directive should listen the click event of the element (button) then toggle the $ctrl.modal.show property.指令应该监听元素(按钮)的点击事件,然后切换$ctrl.modal.show属性。

What I mean with toggling is:我的意思是切换:

$ctrl.modal.show = !$ctrl.modal.show;

How can achieve this scenario using directives?如何使用指令实现这种情况?

To handle click events inside a directive be sure to use $apply :要处理指令内的点击事件,请务必使用$apply

app.directive("myDirective", function() {
    return {
        link: postLink
    }
    function postLink(scope, elem, attrs) {
        elem.on("click", function(ev) {
            scope.$apply(function() {
                //code here
            });
        });
    }
})

AngularJS modifies the normal JavaScript flow by providing its own event processing loop. AngularJS 通过提供自己的事件处理循环来修改正常的 JavaScript 流程。 This splits the JavaScript into classical and AngularJS execution context.这将 JavaScript 分为经典和 AngularJS 执行上下文。 Only operations which are applied in the AngularJS execution context will benefit from AngularJS data-binding, exception handling, property watching, etc... You can also use $apply() to enter the AngularJS execution context from JavaScript.只有在 AngularJS 执行上下文中应用的操作才会受益于 AngularJS 数据绑定、异常处理、属性监视等……您还可以使用$apply()从 JavaScript 进入 AngularJS 执行上下文。

For more information, see有关更多信息,请参阅

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

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