Angular JS在同一个div中限制ng-click事件

时间:2017-08-07 07:31:37

标签: angularjs

当我点击内部标签时会触发这两个功能,我该如何限制它。我只需要在单击时触发onDelete()函数

<div ng-click="ctrl.onEdit()">
{{content}}
<a href="" ng-click="ctrl.onDelete()" > Delete Me !</a>
</div>

4 个答案:

答案 0 :(得分:1)

在ctrl.onDelete($ event)中传递$ event,然后在on delete函数中停止传播它,你需要这个,因为事件向父元素冒泡

 this.onDelete = function (event){
             event.stopPropagation(); 
 }

或者只需在html

中删除功能后再写一下
ng-click="ctrl.onDelete(); $event.stopPropagation();"

答案 1 :(得分:1)

您可以传递$event并使用stopPropagation

来实现这一目标
<div ng-click="onEdit($event)" style="background-color:red;">
  {{content}}
   <a href="" ng-click="onDelete($event)" > Delete Me !</a>
 </div>

JS

$scope.onEdit = function(event){
    console.log("onEdit");
    event.stopPropagation();        
  }

  $scope.onDelete = function(){
    console.log("onDelete");
    event.stopPropagation();        
  }

Demo Plunkr

然而,使用嵌套ng-click是不好的做法。它难以维护并可能导致意外行为。

答案 2 :(得分:0)

<div ng-click="ctrl.onEdit()">
        {{content}}
</div>
<div>
 <a href="" ng-click="ctrl.onDelete()" > Delete Me !</a>
</div>

我认为它会像这样工作

答案 3 :(得分:0)

它被称为event bubbling。您可以传播该事件并像这样取消它

function onDelete($event){
   if($event){
      if ($event.stopPropagation) $event.stopPropagation();
      if ($event.preventDefault) $event.preventDefault();
   }
}

<强> HTML

 <div ng-click="ctrl.onEdit()">
     {{content}}
     <a href="" ng-click="ctrl.onDelete($event)" > Delete Me !</a>
 </div>