触发器<输入类型=“;文件“>用angular程序选择文件

Trigger <input type="file"> file select with angular programatically

本文关键字:文件 程序 选择 gt angular lt 输入 类型 触发器      更新时间:2023-09-26

Im使用ngImgCrop,如本JSFiddle中所示
我试图实现的是,当我显示(使用ng if):时,图像选择框将自动打开

<div ng-if="showImageSelector">
 <div>Select an image file: <input type="file" id="fileInput" /></div>
 <div class="cropArea">
  <img-crop image="myImage" result-image="myCroppedImage"></img-crop>
 </div>
</div>

也就是说:我想用程序打开图像选择窗口,甚至不向用户显示:

<input type="file" id="fileInput" />

Ive尝试在控制器中放入输入的点击事件的几种变体,但都不起作用,到目前为止,Ive尝试了:1.

$timeout(function() {
    angular.element('#fileInput').triggerHandler('click');
  }, 0);

2.

angular.element(document).ready(function () {
    angular.element('#fileInput').triggerHandler('click');
  });

3.

setTimeout(function(){
    angular.element('#fileInput').triggerHandler('click');
  }, 1000);

4.

setTimeout(function(){
    document.getElementById('fileInput').click();
  }, 1000);

对于以编程方式打开文件选择器的触发器,答案是肯定的。

但您需要确保此事件是由用户触发的

例如,你有一个按钮,你在上面附加点击事件。用户点击这个按钮后,在事件处理程序中,你可以通过javascript代码触发,例如document.getElementById('fileInput').click()。这应该行得通。

但是,如果您只想运行几行javascript代码来打开文件选择器而不需要用户点击,这是不可能的,因为这违反了安全策略。

所以我在你的样本中添加了一些代码,

html、

<button ng-click='open()'>Open selector</button>

javascript、

$scope.open = function() {
     document.getElementById('fileInput').click(); //this work
};

希望这能解决你的问题。:)

最终用我的指令包装ngImgCrop,其中iv'e放置了:

$timeout(function () {
      angular.element(document.querySelector('#fileInput')).click();
      $log.debug("poped it");
    }, 250);

在链接函数中。除了我为img选择器显示的真实元素外,iv'e还将其放在了我的index.html:中

<div ng-show="false">
  <my-image-select cropped-image="groupDetails.newPic" return-func="groupDetails.imageSelectFinish"></my-image-select>
</div>

它是有效的。在index.html中没有额外的不可见的my image select,文件选择器只会在第二次尝试时自动打开。