水果的名称是嵌套在a
内的<div ng-repeat=".."></div>
个元素。单击此橙色父div
时,将显示一些隐藏文本。单击水果名称时,它应变为粗体。
问题:点击水果名称后,它会变为粗体 AND 隐藏文字。如果没有显示隐藏文本,我们如何允许水果名称加粗?
我认为这涉及防止点击事件从a
传播到div
,我们该如何做?
Jsfiddle: http://jsfiddle.net/tf4b63km/
点击水果名称之前
点击水果名称后
答案 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树。这将使父事件处理程序不会在子单击时运行。
$event
对象传递给点击处理程序stopPropagation()
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;