gpt4 book ai didi

javascript - Angular.js,取消ng-click事件

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:03:35 25 4
gpt4 key购买 nike

我有这段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');
}
}
})

第一次点击一个按钮,会让它变成红色,并且不会触发任何 Action 。第二次单击,调用操作。离开按钮会重置整个过程。

最佳答案

正如在@Flek 的回答的评论中所讨论的那样,调用属性中定义的函数,

ui:confirm="action()"

使用scope.$eval() :

element.bind('click', function(event) {
scope.$eval(attrs.uiConfirm); // calls action() on the scope
});

关于javascript - Angular.js,取消ng-click事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15385914/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com