在AngularJS触发输入文件单击事件单击、事件、文件、AngularJS

2023-09-13 02:39:55 作者:无伤风雅.

我试图仿效在AngularJS文件输入一个点击事件。我所看到的工作jQuery的范例,但我不想使用jQuery。

\r\r

使用严格的;\r\rangular.module('MyApp的',[])。\r\r控制器('MyCtrl',函数($范围){\r  $ scope.click =功能(){\r    的setTimeout(函数(){\r      VAR元= angular.element(的document.getElementById('输入'));\r      element.triggerHandler('点击');\r      $ scope.clicked = TRUE;\r    },0);\r  };\r});

\r

<脚本SRC =HTTPS://$c$c.angularjs。组织/ 1.3.14 / angular.js>< / SCRIPT>\r< D​​IV NG-应用=MyApp的NG控制器=MyCtrl>\r  <输入ID =输入类型=文件/>\r  <按钮NG点击=点击()>点击ME<!/按钮>\r  < D​​IV NG-IF =点击>被点击的< / DIV>\r< / DIV>

\r\r\r

Angular JavaScript

请注意:出于某种原因,该按钮必须以触发超时功能pssed两次$ P $

我使用的setTimeout 这个帖子。

如何编程单击文件输入,只是AngularJS /香草的JavaScript?

解决方案

您可以简单地使用

 <按钮式=按钮的onclick =的document.getElementById('输入')点击()。>点击ME<!/按钮> 

  $ scope.click =功能(){    的setTimeout(函数(){        的document.getElementById('输入')。点击()        $ scope.clicked = TRUE;    },0);}; 

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?

解决方案

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