阻止Angular中从子元素到父元素的ng-click传播

时间:2015-12-17 05:44:51

标签: javascript jquery angularjs

水果的名称是嵌套在a内的<div ng-repeat=".."></div>个元素。单击此橙色父div时,将显示一些隐藏文本。单击水果名称时,它应变为粗体。

问题:点击水果名称后,它会变为粗体 AND 隐藏文字。如果没有显示隐藏文本,我们如何允许水果名称加粗?

我认为这涉及防止点击事件从a传播到div,我们该如何做?

Jsfiddle: http://jsfiddle.net/tf4b63km/

点击水果名称之前

enter image description here

点击水果名称后

enter image description here

2 个答案:

答案 0 :(得分:4)

您可以通过致电stopPropagation来阻止事件冒泡。在您的情况下,您需要做两件事:

1)将$event传递给makeBold函数:ng-click="makeBold($event, f)"

2)致电stopPropagation

function makeBold($event, f) {
   $event.stopPropagation();
   // ...
}

答案 1 :(得分:1)

e.stopPropagation();函数中使用makeBold来阻止事件冒泡DOM树。这将使父事件处理程序不会在子单击时运行。

  1. $event对象传递给点击处理程序
  2. 在处理程序中,使用stopPropagation()
  3. Updated Fiddle

    &#13;
    &#13;
    var myApp = angular.module('myApp', []);
    
    FruitCtrl = function($scope) {
      $scope.fruits = [{
        title: 'apple',
        color: 'red'
      }, {
        title: 'orange',
        color: 'orange'
      }, {
        title: 'banana',
        color: 'yellow'
      }];
    
      $scope.makeBold = function(e, f) {
        console.log('makeBold')
        f.isBold = 'bold';
    
        // Stop event propagation here
        e.stopPropagation();
      }
    }
    &#13;
    .fruit {
      background: #FF735C;
      width: 100px;
      padding: 10px;
      margin-bottom: 5px;
      border-radius: 4px;
      cursor: pointer;
    }
    .fruit a {
      color: #fff;
    }
    .fruit:hover {
      background: #3D3240;
    }
    &#13;
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
    <div ng-app="myApp">
      <div ng-controller="FruitCtrl">
        <div ng-repeat='f in fruits' class='fruit' ng-click='f.show = !f.show'>
          <a href="#" ng-click='makeBold($event, f)' ng-style='{"font-weight": f.isBold}'>{{ f.title }}</a>
          <!--                           ^^^^^^ Pass event object --->
          <div ng-show='f.show'>
            {{ f.color }}
          </div>
        </div>
      </div>
    </div>
    &#13;
    &#13;
    &#13;