这是一个指令,我试图在其中禁用基于模型值的链接:
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 事件进行的绑定(bind)不起作用,因为 ngClick 似乎正在绑定(bind)我无法控制的自己的处理程序。有什么我可以做的吗?
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 - 在自定义指令中禁用 ngClick 事件处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17820523/