angvee angvee - 4 months ago 11
AngularJS Question

click and run one function of two different function in one div in angular

I create two div and each div had different angular function. I want click one of them using ng-click. if one of div get a click, hope me it will running their own function but in my case it always run both of function. this my code looks like :



this is my html code :

<div ng-controller="Ctrl1">
<div ng-click="titi();" style="width:200px; height:200px; background-color:red;">
<div ng-click="toto();" style="width:100px; height:100px; background-color:yellow;">Click me</div>
</div>
</div>


and this is my angular code :

var app = angular.module('myApp', []);

function Ctrl1($scope) {

$scope.toto = function(){
alert('toto');
};

$scope.titi = function(){
alert('titi');
};
}


if I click yellow div, it show alert toto and titi. And if I click red div, it show alert just titi. All I want is when I click one of them, they will run their own function click. is there something wrong? please help :(

Answer

Here click on the inner element div is propagated to the outer div. Use $event.stopPropagation(); prevent click propagation:

<div ng-controller="Ctrl1">
    <div ng-click="titi();" style="width:200px; height:200px; background-color:red;">
         <div ng-click="toto(); $event.stopPropagation();" style="width:100px; height:100px; background-color:yellow;">Click me</div>
    </div>
</div>