繁体   English   中英

扳机<input type="file">以编程方式选择带有角度的文件

[英]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>

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

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

我尝试在控制器中放入输入的点击事件的几种变体,但它们都不起作用,到目前为止我尝试过: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,在其中放置了:

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

在链接功能中。 除了我为 img 选择器显示的真实元素之外,我把它放在我的 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,文件选择器只会在第二次尝试时自动打开。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM