我有这段html代码
<button ui:confirm ng:click="action"></button>
还有一点 JavaScript。
.directive('uiConfirm', function()
{
return {
restrict: 'A',
link: function(scope, element, attrs)
{
element.bind('click.confirm', function(event)
{
event.preventDefault();
event.stopPropagation();
});
}
}
})
现在,我的目标是在指令内部取消 ng:click 事件。但无论我做什么,ng:click 仍然会被触发。
演示:Fiddle 编辑: 顺便说一句,在这个作用域中引起错误:
element.bind('click.confirm', function(event)
{
causeAnError();
event.preventDefault();
event.stopPropagation();
});
完成了操作,取消了事件传播,但也产生了一个难看的错误 =)
编辑2:最终我找到了一个解决方案!
.directive('uiConfirm', function()
{
return {
restrict: 'A',
link: function(scope, element, attrs)
{
element.bind('click', function(event)
{
scope.$eval(attrs.uiConfirm); // this line of code does the magic!
});
}
}
})
编辑3:
最终解决方案
.directive('uiConfirm', function()
{
return {
restrict: 'A',
link: function(scope, element, attrs)
{
/**
* Clicking the trigger start the confirmation process.
*/
element.bind('click.confirm', function(event)
{
// not confirmed?
if( ! element.data().confirmed)
{
element.data().confirmed = true;
element.addClass('btn-danger');
}
// is already confirmed..
else
{
element.trigger('mouseout.confirm');
scope.$eval(attrs.uiConfirm);
}
});
/**
* Leaving the element, resets the whole process.
*/
element.bind('mouseout.confirm', function()
{
// reset all values
element.data().confirmed = false;
element.removeClass('btn-danger');
});
// reset the whole process on the first run
element.trigger('mouseout.confirm');
}
}
})
第一次点击按钮会将其变成红色,并且不会触发任何动作。第二次点击会调用操作。离开按钮会重置整个过程。
bind('click.confirm')
做了什么?我以前没有见过。 - Mark Rajcok