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

前端 未结 4 853
臣服心动
臣服心动 2021-01-19 08:15

LIVE DEMO

Consider the following myButton directive:

angular.module(\"Demo\", []).directive(\"myButton\", function() {
  return {
    re         


        
相关标签:
4条回答
  • 2021-01-19 08:44

    Why not use the actual button for your button. You could 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 style it to look like your div. See the Short Example I've made.

    0 讨论(0)
  • 2021-01-19 08:46
    <my-button disabled="buttonIsDisabled" 
           ng-click="showSomething = buttonIsDisabled ? showSomething : !showSomething">
    

    or

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

    Is this too simple?

    0 讨论(0)
  • 2021-01-19 08:51

    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.

    0 讨论(0)
  • 2021-01-19 08:58

    Try this in your link function:

    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 deal with cross browser problems. The idea here is to attach our event handler at the head of the click handlers list and use stopImmediatePropagation() to stop current handlers of the same event and bubbling event.

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

    0 讨论(0)
提交回复
热议问题