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

前端之家收集整理的这篇文章主要介绍了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绑定了我自己无法控制的处理程序.有什么我可以做的吗?

jsFiddle:http://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

猜你在找的Angularjs相关文章