Remco Haszing Remco Haszing - 27 days ago 8
HTML Question

Trigger input file click event in AngularJS

I am trying to emulate a click event on a file input in AngularJS. I have seen working jQuery examples, but I don't want to use jQuery.



'use strict';

angular.module('MyApp', []).

controller('MyCtrl', function($scope) {
$scope.click = function() {
setTimeout(function() {
var element = angular.element(document.getElementById('input'));
element.triggerHandler('click');
$scope.clicked = true;
}, 0);
};
});

<script src="https://code.angularjs.org/1.3.14/angular.js"></script>
<div ng-app="MyApp" ng-controller="MyCtrl">
<input id="input" type="file"/>
<button ng-click="click()">Click me!</button>
<div ng-if="clicked">Clicked</div>
</div>





Note: For some reason the button needs to be pressed twice in order to trigger the timeout function.

I am using
setTimeout
because of this post.

How do I programmatically click a file input with just AngularJS / vanilla JavaScript?

Answer Source

You can simply use

 <button type="button" onclick="document.getElementById('input').click()">Click me!</button>

OR

$scope.click = function() {
    setTimeout(function() {
        document.getElementById('input').click()
        $scope.clicked = true;
    }, 0);
};