uladzimir
uladzimir

Reputation: 5689

How to trigger emulate click ngClick from jQuery

How have a link like

<a href="" ng-click="someAction()">Some text</a>

and I want to invoke ngClickaction from jQuery:

$('a').click()

But it doesn't work: someAction() not invoked. Also didn't work

$('a').trigger('click')

Is it possible to invoke someAction() from jQuery?

Upvotes: 5

Views: 10295

Answers (4)

Rupesh
Rupesh

Reputation: 2667

Worked for me the old way document.querySelector('a.btn.btn-info.showmore.ng-scope').click()

Upvotes: 1

Vlad Gurovich
Vlad Gurovich

Reputation: 8463

Nevermind the apply cycles and timeouts, here you are:

$('a').dispatchEvent(new MouseEvent('click', {
 'view': window,
 'bubbles': true,
 'cancelable': true
}));

Upvotes: 4

ivarni
ivarni

Reputation: 17878

I think it's strange that it's not working, I get it working with both

angular.element('a[ng-click="someAction()"]')

and

$('a[ng-click="someAction()"]')

as selectors, and both click() and trigger('click') to fire the clickhandler.

See http://plnkr.co/edit/6VMavwVImXAonSp8xZrI?p=preview (Watch the console)

Upvotes: 4

Max Langerak
Max Langerak

Reputation: 1207

Yes you could, but you should assign an id:

<a id='Button'>SOMETEXT</a>

$("#Button").click(function() {
   alert('clicked');
   someAction();
);

This should fix it.

Upvotes: 0

Related Questions