简体   繁体   中英

jQuery click event does not trigger in AngularJS DOM

I have tried many ways to click a button on click of other button of AngularJS.

Dom element:

<a class="nav-bar-link" ng-click="someMethod()">

Button:

<a class="button">Log in</a>

Expected results

On click of button nav-bar-link should be clicked.


Attempted Solutions

$(document).on('click', '.button', function(event) {
  console.log('came');
  event.preventDefault();
  $(".nav-bar-link").click();
});
$(document).on('click', '.button', function(event) {
  console.log('came');
  event.preventDefault();
  $(".nav-bar-link").triggerHandler('click');;
});
$(document).on('click', '.button', function(event) {
  console.log('came');
  var a = $('nav-bar-link')[0];
  var e = document.createEvent('MouseEvents');
  e.initEvent('click', true, true);
  a.dispatchEvent(e);
});
$(".button").click(function() {
  setTimeout(function() {
    $('.nav-bar-link').trigger('click');
  }, 100);
  return false;
});

These answers were tested from browser console.

Please let me know if there is any solution to trigger the click. Nothing worked from the above solutions.

I would also accept both jQuery and JavaScript solutions.

You should specified type of selector, in your case .nav-bar-link , change

$("nav-bar-link").click(); 

by

$(".nav-bar-link").click(); 

UPDATED

You do not need to write much code to call an event, if you use angular you can use triggerHandler :

$(document).on('click', '.button', function(event) { 
     console.log('came'); 
     angular.element('.nav-bar-link').triggerHandler('click');
});

Result: https://jsfiddle.net/cmedina/4pkdros9/

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