2015-04-23 84 views
1

In this plunk我有兩個div。第一個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; 

}); 
+1

你想'stopPropagation()',不'preventDefault()'。 'preventDefault'用於阻止瀏覽頁面的鏈接,表單提交等 – Phil

回答

4

使用e.stopPropogation()從propogating

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

停止的情況下,應使用e.stopPropagation();

0

是的,使用e.stopProgation(),但請記住,如果你需要的是點擊您的元素後要重新渲染視圖中,您將需要使用$申請例如:

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; 
    }); 
    });