testing
testing

Reputation: 2343

Why is sequence of `on` handler call not in order in angular?

Here is my code

    function linkFunc(scope, element, attr){
        var clickedElsewhere = false;

        $document.on('click', function(){
            clickedElsewhere = false;
            console.log('inside document');

        });

        element.on('click', function(){
            clickedElsewhere = true;
            console.log('inside element');
        });

    }

I am trying to detect on click on my element vs outside of my element.

When I clicked my element here is the result

`clickedElseWhere = false`

console output

inside element
inside document

When I clicked outside of my element here is the result

`clickedElseWhere = false`

console output

inside document

Why is this behavior happening?

Upvotes: 3

Views: 53

Answers (1)

Mathew Berg
Mathew Berg

Reputation: 28750

That's how dom events work, they bubble up and your element is in the document. If you want to stop the bubbling (propagation) you have to tell it too:

    element.on('click', function(event){
        event.stopPropagation();
        clickedElsewhere = true;
        console.log('inside element');
    });

This will make it so that your document event won't fire.

Upvotes: 3

Related Questions