Reputation: 63619
The name of fruits are a
elements nested within a <div ng-repeat=".."></div>
. When this orange parent div
is clicked, some hidden text is shown. When the fruit name is clicked, it should become bold.
Problem: When the fruit name is clicked, it becomes bold AND the hidden text is revealed. How do we allow the fruit name to be bold without the hidden text being revealed?
I believe this involves preventing propogation of the click event from the a
to the div
, how can we do this?
Jsfiddle: http://jsfiddle.net/tf4b63km/
Before clicking on fruit name
After clicking on fruit name
Upvotes: 3
Views: 2523
Reputation: 1188
You can stop event from bubbling up by calling stopPropagation
. In your case you need to do two things:
1) Pass $event
to makeBold
function: ng-click="makeBold($event, f)"
2) Call stopPropagation
function makeBold($event, f) {
$event.stopPropagation();
// ...
}
Upvotes: 6
Reputation: 87203
Use e.stopPropagation();
in the makeBold
function to stop event from bubbling up the DOM tree. This will make the parent event handlers not to run on child click.
$event
object to the click handlerstopPropagation()
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();
}
}
.fruit {
background: #FF735C;
width: 100px;
padding: 10px;
margin-bottom: 5px;
border-radius: 4px;
cursor: pointer;
}
.fruit a {
color: #fff;
}
.fruit:hover {
background: #3D3240;
}
<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>
Upvotes: 1