How to stop ng-click from user directive in AngularJS?

Live demo

Consider the following directive myButton:

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

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

How can I stop ng-clickexecution when I buttonIsDisabledhave it true?

PLAY HERE

+4
source share
4 answers

Why not use the actual button for your button. You can change your directive to:

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

Then tweak it so that it looks like your div. See the Short Example I made.

+2
source

(addEventListener ) ( stopPropagation).

"" , "" ( "" -) "stopPropagation"... ( ).

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

. .

+5

:

link: function(scope, element, attrs) {
      var clickHandlers = $._data(element[0]).events.click;

      clickHandlers.reverse(); //reverse the click event handlers list

      element.on('click', function(event) {
        if (scope.disabled) {
          event.stopImmediatePropagation(); //use stopImmediatePropagation() instead of stopPropagation()
        }
      });

      clickHandlers.reverse(); //reverse the list again to make our function at the head of the list
}

DEMO

This solution uses jQuery to solve cross-browser issues. The idea here is to attach our event handler at the top of the list of click handlers and use stopImmediatePropagation () to stop the current handlers of the same event and bubbling events.

Also take a look at this: jquery: stopPropagation vs stopImmediatePropagation

+1
source
<my-button disabled="buttonIsDisabled" 
       ng-click="showSomething = buttonIsDisabled ? showSomething : !showSomething">

or

<my-button disabled="buttonIsDisabled" 
       ng-click="showSomething = buttonIsDisabled ? function(){} : !showSomething">

It's too easy?

0
source

Source: https://habr.com/ru/post/1538592/


All Articles