如何在不使用getElementById的情况下在输入标签中获取文件属性

angularjs - how to get files attribute in input tag without using getElementById

本文关键字:标签 输入 取文件属性 情况下 getElementById      更新时间:2023-09-26

我正在用AngularJS上传文件。如何获得输入文件,就像普通的JS?

这就是我需要模拟的
HTML:

<input type="file" name="file" id="fileImg" accept="image/*">

JS:

var filesUpload = document.getElementById("fileImg").files

这就是我现在的结果
HTML:

<input type="file" name="file" ng-model="image" accept="image/*">
<input type="button" ng-click="submit()" value="press me">

角:

angular
        .module('app')
        .controller("productsCtrl", function($scope) {
            $scope.image = {};

            $scope.submit = function() {
                var filesUpload = ????????????????
            }
         }

那么,如何使用"getElementById"获取输入withput中的"文件"呢?
注意-不能改变什么,只有"??????"

任何帮助都将不胜感激。
tnx

你可以使用自定义指令

var app = angular.module('App', []);
app.controller('Main', function($scope, $timeout, $rootScope){
    $scope.onSubmit = function(){
        console.log($scope.file);
    }
});
app.directive('fileRead', [function () {
    return {
       scope: {
        fileRead: '='
       },
       link: function (scope, elem, attrs) {
           elem.bind('change', function (event) {
             scope.$apply(function () {
                scope.fileRead = event.target.files[0];
             });
           });
       }
    }
 }]);
使用

 <div ng-app="App">
    <div ng-controller="Main">
        <form ng-submit="onSubmit()">
            <input type="file" name="someName" file-read="file">
            <button type="submit">Submit</button>
        </form>
    </div>
 </div>