How to trigger ngClick programmatically
Asked Answered
K

10

112

I want to trigger ng-click of an element at runtime like:

_ele.click();

OR

_ele.trigger('click', function());

How can this be done?

Kylynn answered 17/3, 2014 at 5:9 Comment(1)
No, i want to know the mechanism through which i can trigger ng-click manually.Kylynn
E
189

The syntax is the following:

function clickOnUpload() {
  $timeout(function() {
    angular.element('#myselector').triggerHandler('click');
  });
};

// Using Angular Extend
angular.extend($scope, {
  clickOnUpload: clickOnUpload
});

// OR Using scope directly
$scope.clickOnUpload = clickOnUpload;

More info on Angular Extend way here.

If you are using old versions of angular, you should use trigger instead of triggerHandler.

If you need to apply stop propagation you can use this method as follows:

<a id="myselector" ng-click="clickOnUpload(); $event.stopPropagation();">
  Something
</a>
Erminois answered 20/6, 2014 at 19:14 Comment(7)
what version of angular are you using. triggerHandler seems to work fine in 1.2.1: jsfiddle.net/t34z7Beachlamar
please explain why $(elem).click() doesn't work with Angular?Satsuma
If you are limited to jqLite and can't use a selector, do this instead: angular.element(document.querySelector('#mySelector')).trigger('click');Monkfish
@DanielNalbach in current (and not so current) Angular versions 1.2+, you have to use triggerHandler instead of triggerConcentre
Yea .trigger() is not a function in jqLiteMarcy
Why did they remove trigger? It seems better/easier than triggerHandler. For one thing, triggerHandler does not even call the default browser click event, only the handlers you already attached.Deceive
I'm not so sure this still works...angularjs 1.6 this seems to not be working with full jqueryChelton
B
84
angular.element(domElement).triggerHandler('click');

EDIT: It appears that you have to break out of the current $apply() cycle. One way to do this is using $timeout():

$timeout(function() {
    angular.element(domElement).triggerHandler('click');
}, 0);

See fiddle: http://jsfiddle.net/t34z7/

Beachlamar answered 17/3, 2014 at 5:18 Comment(12)
even this is nor working, its throwing following error Error: [$rootScope:inprog] errors.angularjs.org/1.2.14/$rootScope/inprog?p0=%24apply at Error (native)Kylynn
Can you replace the body of your click handler function with this line: alert('boom')? Can you see the alert?Beachlamar
You are going to have to show us a test case. Please send a fiddle if you want further assistance.Beachlamar
are you sure triggerHandler will fire ng-click event?Kylynn
jsfiddle.net/U3pVM/3668 here is a small fiddle. Click on third check box and FIRST check box should also get selectedKylynn
You probably want to use Angular's $timeout rather than setTimeout, as $timeout will run an $apply cycle for you if necessary. It also makes your code more testable as ngMock gives you full control over when $timeouts are executed. docs.angularjs.org/api/ng/service/$timeoutDigitalize
Actually this should be $timeout(fn, 0, false); so that it doesn't invoke $apply, shouldn't it?Pinkster
$timeout will break out of the current $apply cycle even with delay=0. So in the context of this question, the third argument is irrelevant.Beachlamar
This should be the accepted answer. triggerHandler works. trigger does not in v1.2.25Sclater
dont forget to add '$event.stopPropagation();' just after the function startBrucine
@Digitalize you sure $timeout is for angular and not jquery, cause when i call $timeout, it say "ReferenceError: $timeout is not defined" ... txtNickName: function () { $timeout(function () { angular.element('#btnStartChat').triggerHandler('click'); //angular.element('#btnStartChat').trigger('click'); }, 0);Maurey
@deadManN $timeout is a service and as such needs to be dependency-injected before you can use it docs.angularjs.org/api/ng/service/$timeoutDigitalize
R
20

This following solution works for me :

angular.element(document.querySelector('#myselector')).click();

instead of :

angular.element('#myselector').triggerHandler('click');
Rosas answered 25/7, 2016 at 13:37 Comment(3)
@DotKu Maybe you are already in a $scope function like when you use in a $timeout function ? In other words, you can't call a $scope.$apply() in a $scope.$apply()... I hope this might helps you.Rosas
@Rosas I found it, it must be placed in $timeout. ThanksOvertask
OMG, Angular totallt ruined it. Why can't they mimick jQuery's $('#element').click()Journal
B
13

Just in case everybody see's it, I added additional duplicating answer with an important line which will not break event propagation

$scope.clickOnUpload = function ($event) {    
    $event.stopPropagation(); // <-- this is important

    $timeout(function() {
        angular.element(domElement).trigger('click');
    }, 0);
};
Brucine answered 1/12, 2014 at 8:38 Comment(1)
Thanks! This finally worked for me in 1.5.11, and full jquery dependency. $timeout(function() { var el = document.getElementsByClassName('fa-chevron-up'); angular.element(el).trigger('click'); }, 0);Sweatshop
A
10

Using plain old JavaScript worked for me:
document.querySelector('#elementName').click();

Adelia answered 21/6, 2017 at 12:25 Comment(1)
Yeah. Works for me. Thanks.Ampere
Q
6

The best solution is to use:

domElement.click()

Because the angularjs triggerHandler(angular.element(domElement).triggerHandler('click')) click events does not bubble up in the DOM hierarchy, but the one above does - just like a normal mouse click.

https://docs.angularjs.org/api/ng/function/angular.element

http://api.jquery.com/triggerhandler/

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click

Quadri answered 26/1, 2017 at 13:24 Comment(0)
R
4

You can do like

$timeout(function() {
   angular.element('#btn2').triggerHandler('click');
});
Rampant answered 17/3, 2014 at 5:48 Comment(1)
I get this error for this solution in my ng 1.5.3 app: Looking up elements via selectors is not supported by jqLite.Keeler
E
1

This code will not work (throw an error when clicked):

$timeout(function() {
   angular.element('#btn2').triggerHandler('click');
});

You need to use the querySelector as follows:

$timeout(function() {
   angular.element(document.querySelector('#btn2')).triggerHandler('click');
});
Ellipsis answered 4/10, 2018 at 13:53 Comment(0)
C
1

Simple sample:

HTML

<div id='player'>
    <div id="my-button" ng-click="someFuntion()">Someone</div>
</div>

JavaScript

$timeout(function() {
    angular.element('#my-button').triggerHandler('click');
}, 0);

What this does is look for the button's id and perform a click action. Voila.

Source: https://techiedan.com/angularjs-how-to-trigger-click/

Canaster answered 31/7, 2019 at 7:38 Comment(0)
S
0

Include following line in your method there you want to trigger click event

angular.element('#btn_you_want_to_click_progmaticallt').triggerHandler('click');
});
Sackey answered 25/6, 2019 at 9:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.