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?
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);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With