我有这段 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 仍然会被触发,无论我做什么。
演示:小提琴
编辑:顺便说一句,在这个范围内导致错误:
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');
}
}
})
第一次点击一个按钮,它会变成红色,并且不会触发任何动作。第二次单击,调用动作。离开按钮会重置整个过程。