3
<div ng-click="process1()" id="1">
    <div ng-click="process2()" id="2">
    </div>
</div>

When I click the div which id is two, it will both trigger process1 and process2,How can I just trigger process2?

Bird Eggegg
  • 449
  • 6
  • 14

3 Answers3

5

You can use directive for this. It will be more generalise to stop event propagation.

HTML

<div ng-click="process1()" id="1">
    <div ng-click="process2()" id="2" stop-event>
    </div>

In controller:

$scope.process1 = function(){
    alert(1);
}

$scope.process2 = function(){
    alert(2);
}

and just use a directive

.directive('stopEvent', function () {
return {
    restrict: 'A',
    link: function (scope, element, attr) {
        element.bind('click', function (e) {
            e.stopPropagation();
        });
    }
}

jsFiddle: http://jsfiddle.net/6m290Lbt/3/

If you wanted, you could make this solution more generic like this answer to a different question: https://stackoverflow.com/a/14547223/347216

Community
  • 1
  • 1
Sourav Mondal
  • 405
  • 2
  • 12
4

I think you should pass the $event from the html in the ng-click of id 2 element and then call the stopPropagation method of that event in the controller.

HTML -

<div ng-click="process1()" id="1">
    <div ng-click="process2($event)" id="2">
    </div>
</div>

and in the controller -:

app.controller('MainCtrl', function($scope) {
    $scope.process1 = function(){
        alert(1);
    }

    $scope.process2 = function(event){
        event.stopPropagation();
        alert(2);
    }
});

JSFiddle - http://jsfiddle.net/SSHYK/131/

Thanks!

0

One solution is to use $event.stopPropagation. Also you should avoid to name elements id with numbers.

<div ng-click="process1();$event.stopPropagation();" id="div1">

event.stopPropagation:

Description: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

plunker

References

event.stopPropagation()

Alex Char
  • 32,879
  • 9
  • 49
  • 70