How to handle click events from inside of the directive?



I have a modal component that takes an object with binding (ng-model). Something like:

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

I’m checking for $ to show/hide the modal:

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

I show/hide modal by setting using ng-click directive:

<button ng-click=" = true"></button>

But this solution is hard to maintain.

I need a directive something like this to toggle modal’s show property:

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

Directive should listen the click event of the element (button) then toggle the $ property.

What I mean with toggling is:

$ = !$;

How can achieve this scenario using directives?


To handle click events inside a directive be sure to use $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. This splits the JavaScript into classical and AngularJS execution context. 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.

For more information, see

Answered By – georgeawg

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More