我有这一块的HTML
I have this piece of html
<button ui:confirm ng:click="action"></button>
和JavaScript代码的
and a bit of JavaScript
.directive('uiConfirm', function()
{
return {
restrict: 'A',
link: function(scope, element, attrs)
{
element.bind('click.confirm', function(event)
{
event.preventDefault();
event.stopPropagation();
});
}
}
})
现在,我想要做的,就是取消NG:点击事件,从指令中。但NG:单击仍然得到的触发,无论我做什么
Now, what I'm trying to do, is to cancel the ng:click event, from within the directive. But the ng:click still get's triggered, no matter what I do.
演示:小提琴
编辑:顺便说一下,在这个范围内,从而导致了一个错误:
By the way, causing an error within the this scope:
element.bind('click.confirm', function(event)
{
causeAnError();
event.preventDefault();
event.stopPropagation();
});
做的伎俩,并canceles事件传播,但也会引发和丑陋的错误=)
Does the trick, and canceles the event propagation, but also throws and ugly error =)
编辑2:最后,我已经找到了解决办法!
Edit 2: Finally I've found a solution!
.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');
}
}
})
点击一个按钮,在第一时间,要让它红色,并且不会触发任何动作。点击第二次,调用动作。离开按钮重置的整个过程。
Clicking a button the first time, gonna make it red, and doesn't trigger any action. Clicking a second time, calls the action. Leaving the button resets the whole process.
推荐答案
作为对@ Flek的答复意见的讨论,来调用属性定义的函数,
As discussed in the comments on @Flek's answer, to call a function defined in an attribute,
ui:confirm="action()"
使用范围$的eval():
element.bind('click', function(event) {
scope.$eval(attrs.uiConfirm); // calls action() on the scope
});
相关推荐
最新文章