Angular:单击div时防止默认不起作用

时间:2015-04-23 04:13:16

标签: angularjs

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;

});

3 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:1)

您应该使用e.stopPropagation();

答案 2 :(得分:0)

是的,使用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;
    });
  });