16

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?

Vivz
  • 6,625
  • 2
  • 17
  • 33
Remco Haszing
  • 7,178
  • 4
  • 40
  • 83
  • 1
    The code in the question as well as the proposed answer is a well-known anti-pattern in Angular.js - don't do DOM manipulation in your controllers, unless it's in a directive controller. – yangmillstheory Feb 17 '16 at 22:13

2 Answers2

41

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);
};
Satpal
  • 132,252
  • 13
  • 159
  • 168
  • 2
    Hi, sometimes it's opened multiple times, any way to prevent that ? – Liad Livnat Feb 09 '16 at 09:09
  • 5
    I'm sure @LiadLivnat already solved his issue, but just in case anyone stumbles upon this and has the same issue; This happens when you put the `` inside the element that's supposed to trigger the click on input. `
    ` will trigger infinite clicks on that element. `
    ` works just fine :)
    – serv-bot 22 Sep 17 '16 at 06:58
0

Here's how to trigger file of type 'file' or open select-file window when click on icon, button or span as you like ;)

css :

.attachImageForCommentsIcon{
  padding-top: 14px;
  padding-right: 6px;
  outline:none;
  cursor:pointer;
}

HTML :

<input id="myInput" type="file" style="visibility:hidden" ng-file-model=""/>
<i onclick="$('#myInput').click();" class="attachImageForCommentsIcon blue-2 right-position material-icons">image</i>

all credits goes for this answer : https://stackoverflow.com/questions/8595389/programmatically-trigger-select-file-dialog-box

Thus, we customized file input tag using this way.

Abdallah Okasha
  • 1,879
  • 17
  • 20