加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

AngularJS使用指令来阻止其他指令执行

发布时间:2020-12-17 17:13:22 所属栏目:安全 来源:网络整理
导读:我的Angular应用程序中的某些操作需要注册用户.如果用户未注册,我们希望显示“注册模式”并阻止原始操作. 这些操作可以通过ng-click或任何其他“click binding”指令触发(例如’modal-toggle’指令). 所以我找到了这个解决方案:https://stackoverflow.com/a
我的Angular应用程序中的某些操作需要注册用户.如果用户未注册,我们希望显示“注册模式”并阻止原始操作.

这些操作可以通过ng-click或任何其他“click binding”指令触发(例如’modal-toggle’指令).

所以我找到了这个解决方案:https://stackoverflow.com/a/16211108/2719044

这非常酷,但只适用于ng-click.

我首先想要使指令的“终端”属性动态,但无法设法做到这一点.

因此,我们的想法是将“terminal”设置为true并手动阻止指令中的默认点击操作.

这是我的DOM

<!-- This can work with terminal:true and scope.$eval(attrs.ngClick) (see example above) -->
<div user-needed ng-click="myAction()">Do it !</div> 

<!-- This doesn't work. I can't manage to prevent the modal-toggle to be executed -->
<div user-needed modal-toggle="my-modal-id-yey">Show yourself modal !</div>

而我的指令(不起作用……)

// First try (with terminal:true)
app.directive('userNeeded',function() {
    return {
        priority: -100,terminal: true,restrict: 'A',link: function(scope,element,attrs) {
            element.bind('click',function(e) {
                if(isRegistered()) {
                    // Here we do the action like scope.$eval or something
                }
            });
        }
    };
});

// Second try (with stopPropagation)
app.directive('userNeeded',function() {
    return {
        priority: -100
        restrict: 'A',function(e) {
                if(!isRegistered()) {
                    e.stopPropagation();
                }
            });
        }
    };
});

……这就是我在这里的原因.任何的想法 ?

非常感谢.

解决方法

你非常接近.而不是stopPropagation你需要stopImmediatePropagation. @Dave在 this StackOverflow answer中总结了两者之间的差异:

stopPropagation will prevent any parent handlers from being
executed while stopImmediatePropagation will do the same but
also
prevent other handlers from executing.

所以要修复代码,我们要做的就是换掉那个方法和Voilà:

app.directive('userNeeded',function(e) {
                if(!isRegistered()) {
                    e.stopImmediatePropagation();
                }
            });
        }
    };
});

这是工作代码的example Plunker.在示例中,我稍微修改了指令,允许通过将值直接传递给element.bind函数来指定特定事件(例如user-needed =“submit”);但是,它默认为“点击”.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读