Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 279
Remco Haszing Avatar asked Feb 27 '15 10:02

Remco Haszing


1 Answers

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);
};
like image 99
Satpal Avatar answered Nov 20 '22 04:11

Satpal