17

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?

1
  • 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. Commented Feb 17, 2016 at 22:13

2 Answers 2

42

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);
};
Sign up to request clarification or add additional context in comments.

2 Comments

Hi, sometimes it's opened multiple times, any way to prevent that ?
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 <input> inside the element that's supposed to trigger the click on input. <div onClick="document.getElementById('input').click()"><input/></div> will trigger infinite clicks on that element. <input/><div onClick="document.getElementById('input').click()"></div> works just fine :)
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.

1 Comment

That looks like jQuery (OP doesn't want to use jQuery).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.