AngularJS使用指令来阻止其他指令执行
我的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中总结了两者之间的差异:
所以要修复代码,我们要做的就是换掉那个方法和Voilà: app.directive('userNeeded',function(e) { if(!isRegistered()) { e.stopImmediatePropagation(); } }); } }; }); 这是工作代码的example Plunker.在示例中,我稍微修改了指令,允许通过将值直接传递给element.bind函数来指定特定事件(例如user-needed =“submit”);但是,它默认为“点击”. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- Getting Started with AngularJS 1.5 and ES6: part 3
- angular 系列八 ui-router详细介绍及ngRoute工具区别
- 一个涉及到使用webservice的,对事务和并发控制要求很高的项
- 使用AGSJSONRequestOperation完成webservice资源的请求
- Scala(或Java)中通用函数的专业化
- angularjs – 将角度模板分割成多个小模板
- scala – Spark:分解结构的数据帧数组并附加id
- angularjs – angular-ui-bootstrap模态不传回结果
- vim – MiniBufExplorer和NERD_Tree关闭缓冲意外行为
- Angular2:CoreModule与SharedModule