0

Let's say I have a DIV with a function specified to be called when clicked on it by ng-click.

Inside this DIV there's a BUTTON which also have a function to be called when clicked on, specified by ng-click.

When I click the button, both the DIV's click and the BUTTON's click functions are called. How do I make that only the BUTTON's function is called?

I have set up this fiddle for better illustrate what I mean. Below is the code:

HTML:

<body ng-app="Test">
    <section ng-controller="TestCtrl as ctrl">
        <div class="square" ng-click="ctrl.divClick()">
            <span>My text</span>
            <button ng-click="ctrl.buttonClick()" >My button</button>
        </div>
    </section>
</body>

JavaScript:

(function() {
    var app = angular.module('Test', []);

    app.controller('TestCtrl', [function() {
        this.divClick = function() {
            alert('div clicked');            
        };

        this.buttonClick = function() {
            alert('button clicked');
        }
    }]);
})();

EDIT:

As suggested by akonsu, I just need to stop the event propagation. This worked for me. Here's an updated Fiddle showing how it works.

Community
  • 1
  • 1
Bruno Finger
  • 2,105
  • 3
  • 27
  • 47
  • possible duplicate of [AngularJS ng-click stopPropagation](http://stackoverflow.com/questions/20300866/angularjs-ng-click-stoppropagation) – Gruff Bunny Nov 13 '14 at 16:18

1 Answers1

2

Just stop propagation of the event:

<button ng-click="ctrl.buttonClick($event)">

this.buttonClick = function(e) {
  e.stopPropagation();
  alert('button clicked');
}
akonsu
  • 28,824
  • 33
  • 119
  • 194
  • Wow that was simpler than I expected. Thanks, I'll update my question and Fiddle with your suggestion. – Bruno Finger Nov 13 '14 at 16:17
  • I updated the fiddle to show this but you beat me to it, http://jsfiddle.net/cj5rc6h2/3/ @BrunoFinger, don't forget to accept akonsu's answer – Dai Nov 13 '14 at 16:18