我的 Angular 应用程序中的某些操作需要用户注册。如果用户未注册,我们希望显示“注册模式”并阻止原始操作。

这些操作可以通过 ng-click 或任何其他“点击绑定”指令(例如“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',
        link: function(scope, element, attrs) {
            element.bind('click', function(e) {
                if(!isRegistered()) {
                    e.stopPropagation();
                }
            });
        }
    };
});

...这就是我来这里的原因。任何想法 ?

多谢。

有帮助吗?

解决方案

你们非常亲密。你需要 stop 而不是 stopPropagation即时传播。两者的区别总结为 这个 StackOverflow 答案 通过@戴夫:

stopPropagation 将防止任何 家长 在执行时执行的处理者 stopImmediatePropagation 也会做同样的事 但是也 阻止其他处理程序执行。

因此,要修复代码,我们所要做的就是替换该方法,瞧:

app.directive('userNeeded', function() {
    return {
        priority: -100
        restrict: 'A',
        link: function(scope, element, attrs) {
            element.bind('click', function(e) {
                if(!isRegistered()) {
                    e.stopImmediatePropagation();
                }
            });
        }
    };
});

这是一个 例子 笨蛋 工作代码。在示例中,我稍微修改了指令以允许指定特定事件(例如 user-needed="submit")通过将值直接传递给 element.bind 功能;但是,它默认为“单击”。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top