Two nested click events with angular

I have an 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 identifier myId , then both functions start, but I want the test2 function to run. How can i do this?

+53
javascript function angularjs
Mar 13 '13 at 16:02
source share
3 answers

All you have to do is stop the spread / bubbling of events.

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 look like this, you will only get test2 in the console when you click myId DIV. Without $event.stopPropagation() you get test2 and then test in the console output window.

 $scope.test = function() { console.info('test'); } $scope.test2 = function() { console.info('test2'); } 
+101
Mar 13 '13 at 16:17
source share

Same as tom, but slightly 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") } 
+29
Mar 13 '13 at 17:51
source share

Here is a directive based on another question that supports ng-href links.

Directive

 'use strict'; var myApp = angular.module('myApp', [ 'ngAnimate' ]); /** * @ngdoc directive * @name myMobileApp.directive:stopEvent * @description Allow normal ng-href links in a list where each list element itselve has an ng-click attached. */ angular.module('myApp') .directive('stopEvent', function($location, $rootScope) { return { restrict: 'A', link: function(scope, element) { element.bind('click', function(event) { // other ng-click handlers shouldn't be triggered event.stopPropagation(event); if(element && element[0] && element[0].href && element[0].pathname) { // don't normaly open links as it would create a reload. event.preventDefault(event); $rootScope.$apply(function() { $location.path( element[0].pathname ); }); } }); } }; }) .controller('TestCtrl', ['$rootScope', '$scope', 'Profile', '$location', '$http', '$log', function($rootScope, $scope, Profile, $location, $http, $log) { $scope.profiles = [{'a':1,'b':2},{'a':3,'b':3}]; $scope.goToURL = function(path, $event) { $event.stopPropagation($event); $location.path(path); }; } ]); 
  <div ng-repeat="x in profiles" ng-click="goToURL('/profiles/' + xa, $event)"> <a stop-event ng-href="/profiles/{{xb}}">{{x}}</a> </div> 
+1
Dec 10 '14 at 12:57
source share



All Articles