如何触发元素点击角度js?

时间:2018-05-19 15:11:11

标签: angularjs

我有一个输入文件,它是隐藏的。我想在单击按钮后触发输入文件,但我的代码不起作用。它需要做些什么改变才能发挥作用?

HTML:

<input type="file" ng-model="data.file" id="upload" style="display:none;">
<button type="button" ng-click="browseFile()">Choose a file</button>

JavaScript的:

$scope.browseFile = function () {
  angular.element(document.querySelector('#upload')).triggerHandler('click'); 
 }

2 个答案:

答案 0 :(得分:4)

在html中使用类似下面的内容

<img id="preview_image" src="" accept="image/*" class="upload_img" alt="">

<input id="image_upload" ng-model="file" type="file" class="upload_image_file" />

在控制器中使用$watch

$scope.$watch("file", function() {
  readURL(angular.element("#image_upload")[0]);
});

function readURL(input) {
  if (input && input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function(e) {
      angular.element("#preview_image").attr("src", e.target.result);
      vm.base64File = e.target.result;
    };
    reader.readAsDataURL(input.files[0]);
  }
}

有关详情,请参阅herehere

<强>更新

var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
  $scope.file = '';

  $scope.$watch("file", function() {
    console.log($scope.file)
  });
});
app.directive('fileModel', ['$parse', function($parse) {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      var model = $parse(attrs.fileModel);
      var modelSetter = model.assign;

      element.bind('change', function() {
        scope.$apply(function() {
          modelSetter(scope, element[0].files[0]);
        });
      });
    }
  };
}]);
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.js"></script>

<body>
  <div ng-app="myApp" ng-controller="myCtrl">
    <label class="upload_image_label" for="image_upload">
      choose file
      <input id="image_upload" file-model="file" type="file" style="display:none" />
    </label>

    <hr> <br> File: {{file}}

  </div>
</body>

</html>

答案 1 :(得分:0)

正如adardesign所说

  

这是出于安全限制   我发现安全限制仅在

<input type="file"/>
  

设置为display:none;或者是可见性:隐藏。   所以我尝试通过设置将其定位在视口之外   position:absolute和top:-100px;并且它有效。

您可以在此帖中找到更多信息:Jquery trigger file input