Angularjs doesn't trigger event handled by addEventListener

I'm trying to trigger event on a <A> element with mousedown event handled by addEventListener call but I don't know why it doesn't work.
I tried to use angular.element(el).triggerHandler('click'); but it only triggers event handler specified via ng-click.

In the code below when I click on 'trigger' link only 'first' is printed to console. How do I make it print 'zero' as well?

JSBin link

HTML:

<a id='zero' href="#">zero</a><br/>
<a id="first" href="" ng-click="firstLinkClick()">first</a>
</br>
<a id="trigger" href="" ng-click="triggerLinkClick()">trigger</a>

Javascript:

document.getElementById('zero').addEventListener('click', function() {
  console.log('zero');
}, false);

app.controller('myCtrl', function myCtrl($timeout, $scope) {
  $scope.firstLinkClick = function() {
    console.log('first');
  };

  $scope.triggerLinkClick = function() {
    $timeout(function() {
      var el = document.getElementById('zero');
      angular.element(el).triggerHandler('click');
    }, 100);

    $timeout(function() {
      var el = document.getElementById('first');
      angular.element(el).triggerHandler('click');
    }, 100);
  };
});

Answers:

Answer

Angular uses jqLite internally. If you load jQuery before Angular it will use jQuery instead of jqLite.

triggerHandler only triggers events that are added by jqLite/jQuery.

To trigger events added by addEventListener you need to use the standard API.

For example:

var el = document.getElementById('zero');
el.click();

Or:

var el = document.getElementById('zero');
el.dispatchEvent(new Event('click'));

If you need to support older browsers you can start by reading here.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.