Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop ng-click from a custom directive in AngularJS?

LIVE DEMO

Consider the following myButton directive:

angular.module("Demo", []).directive("myButton", function() {
  return {
    restrict : "E",
    replace: true,
    scope: {
      disabled: "="
    },
    transclude: true,
    template: "<div class='my-button' ng-class='{ \"my-button-disabled\": disabled }' ng-transclude></div>",
  };
});

which can be used like this:

<my-button disabled="buttonIsDisabled" 
           ng-click="showSomething = !showSomething">
  Toggle Something
</my-button>

How could I stop ng-click from executing when buttonIsDisabled is true?

PLAYGROUND HERE

like image 680
Misha Moroshko Avatar asked Feb 14 '23 02:02

Misha Moroshko


1 Answers

You could use capture (addEventListener's optional third parameter) and stop the propagation of the event (using stopPropagation).

"Capture" allows you to catch the event before it reaches the "bubble" phase (when the triggering of "normal" event-listeners happens) and "stopPropagation" will...stop the propagation of the event (so it never reaches the bubbling phase).

element[0].addEventListener('click', function (evt) {
    if (scope.disabled) {
        console.log('Stopped ng-click here');
        evt.preventDefault();
        evt.stopPropagation();
    }
}, true);

See, also, this short demo.

like image 163
gkalpak Avatar answered Mar 06 '23 02:03

gkalpak