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

前端 未结 4 854
臣服心动
臣服心动 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: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

提交回复
热议问题