Javascript 在 AngularJS 中触发输入文件点击事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28762293/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:21:14  来源:igfitidea点击:

Trigger input file click event in AngularJS

javascripthtmlangularjs

提问by Remco Haszing

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.

我正在尝试在 AngularJS 中的文件输入上模拟单击事件。我看过有效的 jQuery 示例,但我不想使用 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 setTimeoutbecause of this post.

setTimeout因为这篇文章,我正在使用。

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

如何仅使用 AngularJS / vanilla JavaScript 以编程方式单击文件输入?

回答by Satpal

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);
};

回答by Abdallah Okasha

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

以下是如何在单击图标、按钮或跨度时触发“文件”类型的文件打开选择文件窗口;)

css :

css :

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

HTML :

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

这个答案的所有功劳:https: //stackoverflow.com/questions/8595389/programmatically-trigger-select-file-dialog-box

Thus, we customizedfile input tag using this way.

因此,我们使用这种方式自定义了文件输入标签。