微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

angularjs – 在自定义指令中禁用ngClick事件处理

这是一个指令,我试图根据模型值禁用链接
app.directive('disableable',function($parse){
    return {
        restrict: 'C',require: '?ngClick',link: function (scope,elem,attrs,ngClick) {
            if (attrs.disable){
                var disable = $parse(attrs.disable);

                elem.bind('click',function (e) {
                    if (disable(scope)){
                        e.preventDefault();
                        return false;
                    }

                    return true;
                });

                scope.$watch(disable,function (val) {
                    if (val){
                        elem.addClass('disabled');
                        elem.css('cursor','default');
                    }
                    else {
                        elem.removeClass('disabled');
                        elem.css('cursor','pointer');
                    }
                });
             }
         }
     };
});

我希望能够禁用所有链接操作,无论他们是使用简单的href还是ngClick操作.由于preventDefault调用,Hrefs正常工作,但我无法弄清楚如何深入研究ngClick并防止它被触发.我在click事件上执行的绑定不起作用,因为似乎ngClick绑定了我自己无法控制的处理程序.有什么我可以做的吗?

jsfiddlehttp://jsfiddle.net/KQQD2/2/

使用event.stopImmediatePropagation.

MDN开始:

If several listeners are attached to the same element for the same
event type,they are called in order in which they have been added. If
during one such call,event.stopImmediatePropagation() is called,no
remaining listeners will be called.

...
elem.bind('click',function (e) {
  if (disable(scope)){
    e.stopImmediatePropagation();
    return false;
  }

  return true;
});
...

WORKING FIDDLE

原文地址:https://www.jb51.cc/angularjs/141462.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐