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

前端 未结 15 1539
傲寒
傲寒 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:35

    I've expanded on @Stuart Axon's idea to add two-way binding for the file input (i.e. allow resetting the input by resetting the model value back to null):

    app.directive('bindFile', [function () {
        return {
            require: "ngModel",
            restrict: 'A',
            link: function ($scope, el, attrs, ngModel) {
                el.bind('change', function (event) {
                    ngModel.$setViewValue(event.target.files[0]);
                    $scope.$apply();
                });
    
                $scope.$watch(function () {
                    return ngModel.$viewValue;
                }, function (value) {
                    if (!value) {
                        el.val("");
                    }
                });
            }
        };
    }]);
    

    Demo

提交回复
热议问题