Search code examples
javascripthtmlangularjsfile-uploadng-file-upload

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


I'm Uploading files with AngularJS. How to get the input files just like regular JS?

This is what I need to simulate exactly
HTML:

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

JS:

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

This is what I have now
HTML:

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

Angular:

angular
        .module('app')
        .controller("productsCtrl", function($scope) {

            $scope.image = {};


            $scope.submit = function() {

                var filesUpload = ????????????????
            }
         }

So, how to get the "files" in the input withput using "getElementById" ?
notice - can't change nothing , only the "??????"

any help will be appreciated..
tnx


Solution

  • You can use custom directive

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

    usage

     <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>