How to trigger ngClick programmatically

2019-01-03 04:54发布

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

_ele.click();

OR

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

How can this be done?

8条回答
闹够了就滚
2楼-- · 2019-01-03 05:09

This following solution works for me :

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

instead of :

angular.element('#myselector').triggerHandler('click');
查看更多
孤傲高冷的网名
3楼-- · 2019-01-03 05:13

You can do like

$timeout(function() {
   angular.element('#btn2').triggerHandler('click');
});
查看更多
我命由我不由天
4楼-- · 2019-01-03 05:13

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');
});
查看更多
做自己的国王
5楼-- · 2019-01-03 05:14

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

查看更多
兄弟一词,经得起流年.
6楼-- · 2019-01-03 05:17

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);
};
查看更多
爱情/是我丢掉的垃圾
7楼-- · 2019-01-03 05:17

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

查看更多
登录 后发表回答