How to trigger ngClick programmatically How to trigger ngClick programmatically angularjs angularjs

How to trigger ngClick programmatically


The syntax is the following:

function clickOnUpload() {  $timeout(function() {    angular.element('#myselector').triggerHandler('click');  });};// Using Angular Extendangular.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>


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/


This following solution works for me :

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

instead of :

angular.element('#myselector').triggerHandler('click');