【问题标题】:Angular: prevent default not working when clicking on divAngular:单击div时防止默认值不起作用
【发布时间】:2015-04-23 04:13:15
【问题描述】:

In this plunk 我有两个 div。第一个 div(橙色)包含第二个 div(蓝色)。目标是在您单击 div 时显示警报。

如果您单击橙色 div(指令 dir1),您将看到警报。但是如果你点击蓝色的 div(指令 dir2),你会看到 两个 警报,因为阻止默认 e.preventDefault() 不会停止事件链。如何使这项工作?

HTML:

  <div dir1 style="width:200px;height:200px;background-color:orange">
       <div dir2 style="width:100px;height:100px;background-color:blue"> </div>
 </div>

Javascript:

app.directive('dir1', function() {

    var directive = {};
    directive.restrict = 'EA';

    directive.link = function(scope, element, attrs) {

        element.bind('click', function() {
            alert('clicked on dir1');
        });
    }

    return directive;

});



app.directive('dir2', function() {

    var directive = {};
    directive.restrict = 'EA';

    directive.link = function(scope, element, attrs) {

        element.bind('click', function(e) {
            e.preventDefault();
            alert('clicked on dir2');
        });
    }

   return directive;

});

【问题讨论】:

  • 你想要stopPropagation(),而不是preventDefault()preventDefault 用于阻止链接离开页面、表单提交等操作

标签: angularjs


【解决方案1】:

使用 e.stopPropogation() 阻止事件传播

element.bind('click', function(e) {
               e.stopPropagation();
              alert('clicked on dir2');
});

【讨论】:

    【解决方案2】:

    你应该使用e.stopPropagation();

    【讨论】:

      【解决方案3】:

      是的,使用 e.stopProgation() 但请记住,如果您需要在单击元素后重新渲染视图,则需要使用 $apply 例如:

        element.on('click', function(event){
          event.stopPropagation();
          // In order to work with stopPropagation and two data way binding
          // if you don't use scope.$apply in my case the model is not updated in the view when I click on the element that has my directive
          scope.$apply(function () {
            scope.myModel.updateAttributeStatus = true;
          });
        });
      

      【讨论】:

        最近更新 更多