4

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);
  };
});
Mr Lister
  • 45,515
  • 15
  • 108
  • 150
Yaiba
  • 571
  • 7
  • 14
  • bind the click event to `#zero` with angularjs as well. just like you did with the other two. why you need to do it outside of angular? – Aᴍɪʀ Jan 15 '16 at 05:18
  • @Amir: #zero is an element generated by 3rd library so I can't change it. I want to simulate user behavior to click on it. – Yaiba Jan 16 '16 at 01:31
  • @georgeawg: Thank you for the information, but I'm not sure how it will solve my problem? Could you give an example? – Yaiba Jan 16 '16 at 01:33

1 Answers1

4

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.

Community
  • 1
  • 1
tasseKATT
  • 38,470
  • 8
  • 84
  • 65