以编程方式使用 angular 触发 <input type="file"> 文件 select

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

我使用的是 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>

即:我想以编程方式打开图像选择 window,甚至不向用户显示:

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

我试过在控制器中放入输入的点击事件的几种变体,但其中 none 有效,到目前为止我试过: 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 代码来打开文件选择器 而无需用户单击 ,那是不可能的,因为违反安全政策。

所以我added some code to your sample,

html,

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

javascript,

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

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

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

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

在 link 函数中。 除了我为 img select 显示的真实元素,或者,我把它放在我的 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,文件选择器仅在第二次尝试时自动打开。