Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two nested click events with angularjs

I have a HTML structure like this:

<div ng-click="test()">     <div id="myId" ng-click="test2()"></div>     <div></div>     ... </div> 

Currently when I click on the div with the id myId then both functions get triggered, but I want that just test2 function get triggered. How can I do that?

like image 765
Safari Avatar asked Mar 13 '13 16:03

Safari


2 Answers

All you need to do is to stop event propagation/bubbling.

This code will help you:

<div ng-click="test()">ZZZZZ     <div id="myId" ng-click="test2();$event.stopPropagation()">XXXXX</div>     <div>YYYYYY</div>     ... </div> 

If your test and test2 functions would look as follows, you would get only test2 in your console when clicking on myId DIV. Without $event.stopPropagation() you would get test2 followed by test in the console output window.

$scope.test = function() {     console.info('test'); } $scope.test2 = function() {     console.info('test2'); } 
like image 108
Tom Avatar answered Sep 20 '22 13:09

Tom


Same as tom's answer, but little different.

        <div ng-click="test()">             <div id="myId" ng-click="test2($event)">child</div>         </div>          $scope.test2 =function($event){             $event.stopPropagation();             console.log("from test2")         }         $scope.test =function(){             console.log("from test")         } 
like image 43
Rajkamal Subramanian Avatar answered Sep 20 '22 13:09

Rajkamal Subramanian