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?

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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!

Comments

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.