mos mos - 5 months ago 38
Javascript Question

js how to avoid unwanted click

I'm using angular.js and I have a table where each row is able to click, using ng-click="launchMethodRow", but in a determinate column in the row I have a button, when I clicked in that button, funcionality of this button is trigered (ng-click="launchMethodButton"), but also the method for the row is launched. How can I do to avoid this behavior? I want when I click the button, only the method that the button responds run and not the method for row.

Answer

You can catch the event associated with the click and prevent it from propagating.

Lets say you have a row and a button like so:

<div class="row" ng-click="launchMethodRow()">
    <button ng-click="launchMethodButton($event)"></button>
</div>

For the button ng-click pass the click event ($event) down to the callback function. And in the launchMethodButton function, stop event propagation.

$scope.launchMethodButton = function(event){
    event.stopPropagation();
    // execute button click logic
}

OR

Alternatively, you could wrap propagation stopping logic into a directive and can apply that to the button and that way you wouldn't have to do that logic in controller.

angular.module('someModule', []).directive('stopClickPropagation', function () {
    return {
        restrict: "A",
        link: function (scope, element) {
            element.bind('click', function (e) {
                e.stopPropagation();
            });
        }
    }
});

<div class="row" ng-click="launchMethodRow()">
        <button ng-click="launchMethodButton()" stop-click-propagation></button>
 </div>