简体   繁体   中英

Angular directive with click event gets called twice

I'm having an issue where my click event is getting called twice. Not sure what I'm missing but I've only included this directive once in my application. I have tried adding the directive to one element only but the call is still happening twice.

Can someone take a look at the code and tell me what i'm missing please?

angular.module('mymodule', [])
.directive('mydirective', function () {
    return {
        restrict: 'AE',
        link: function ($scope, $element, $attrs) {

            $element.children().bind('click', function () {

                console.log("test" + this);

                if ($element.hasClass('active')) {
                    $element.removeClass('active');
                    return;
                } else if (!$element.hasClass('active')) {
                    $element.addClass('active');
                    return;
                }
            });
        }
    }
});

use this inside the click function to stop bubbling the event

 e.stopPropagation();

To know more check this

I know I'm late in answering this, and a few months back I was facing this issue too. However, a gentleman over here asked me to append this into the directive. And, it worked great!

e.stopImmediatePropagation();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM