AngularJs: How to check for changes in file input fields?

前端 未结 15 1530
傲寒
傲寒 2020-11-22 09:06

I am new to angular. I am trying to read the uploaded file path from HTML \'file\' field whenever a \'change\' happens on this field. If i use \'onChange\' it works but when

15条回答
  •  时光说笑
    2020-11-22 09:34

    This is a refinement of some of the other ones around, the data will end up in an ng-model, which is normally what you want.

    Markup (just make an attribute data-file so the directive can find it)

    
    

    JS

    app.directive('file', function() {
        return {
            require:"ngModel",
            restrict: 'A',
            link: function($scope, el, attrs, ngModel){
                el.bind('change', function(event){
                    var files = event.target.files;
                    var file = files[0];
    
                    ngModel.$setViewValue(file);
                    $scope.$apply();
                });
            }
        };
    });
    

提交回复
热议问题