Search code examples
angularjsangularjs-directiveangularjs-events

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 $ctrl.ngModel.show to show/hide the modal:

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

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

<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:

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

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

What I mean with toggling is:

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

How can achieve this scenario using directives?


Solution

  • 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