如何停止AngularJS中自定义指令的ng-click?

时间:2014-04-29 13:30:52

标签: angularjs angularjs-directive

LIVE DEMO

考虑以下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>",
  };
});

可以这样使用:

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

ng-click buttonIsDisabled时如何阻止true执行?

PLAYGROUND HERE

4 个答案:

答案 0 :(得分:5)

您可以使用捕获( addEventListener 的可选第三个参数)并停止事件的传播(使用 stopPropagation )。< / p>

“捕获”允许您在事件到达“泡沫”阶段之前捕获事件(当触发“正常”事件监听器时)和“stopPropagation”将...停止事件的传播(所以它永远不会到达冒泡阶段)。

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

另请参阅此 short demo

答案 1 :(得分:2)

为什么不使用按钮的实际按钮。您可以将指令更改为:

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>"
  };
});

然后将它设计为看起来像你的div。请参阅我制作的Short Example

答案 2 :(得分:1)

在链接功能中尝试此操作:

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

此解决方案使用jQuery来处理跨浏览器问题。这里的想法是在点击处理程序列表的头部附加我们的事件处理程序,并使用 stopImmediatePropagation()来停止同一事件和冒泡事件的当前处理程序。

另请看一下:jquery: stopPropagation vs stopImmediatePropagation

答案 3 :(得分:0)

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

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

这太简单了吗?