簡體   English   中英

如何在angularjs中使用必填項驗證文件?

[英]How to validate files with required in angularjs?

嗨,我正在開發angularjs應用程序。 我有文件上傳模塊。 下面是我的html代碼。

<input type="file"  file-modelsr="myFileID" name="fileupld" valid-files required />

在提交表單時,我正在嘗試獲取以下內容。

console.log(form2.fileupld.$valid);

這總是讓我不確定。 如何在提交表單時檢查文件是否已上傳?

我用下面的指令。

myapp.directive('validFiles', function () {
    return {
        require: 'ngModel',
        link: function (scope, el, attrs, ngModel) {
            //change event is fired when file is selected
            el.bind('change', function () {
                debugger;
                scope.$apply(function () {
                    ngModel.$setViewValue(el.val());
                    ngModel.$render();
                })
            })
        }
    }
})

我使用以下指令上傳文件。

myapp.directive('fileModelsr', ['$parse', function ($parse) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            var model = $parse(attrs.fileModelsr);
            var modelSetter = model.assign;
            element.bind('change', function () {
                scope.$apply(function () {
                    modelSetter(scope, element[0].files[0]);
                });
            });
        }
    };
}]);

如何在AngularJS中應用所需的文件驗證?

您可以將fileModel指令更改為以下內容,並擺脫validFiles指令。 檢查您的fileModelsr是否具有任何值,然后根據此值進行驗證。

JS

.directive('fileModel', ['$parse', '$rootScope', function($parse, $rootScope) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            var model = $parse(attrs.fileModelsr);
            var modelSetter = model.assign;
            element.bind('change', function() {
                scope.$apply(function() {
                    modelSetter(scope, element[0].files[0]);
                    if (element[0].files[0]) {
                        $rootScope.fileUploaded = true;
                    }
                });
            });
        }
    };
}])

HTML

<input type="file" file-modelsr="myFileID" name="fileupld" required />
<button type="submit" name="submit" class="btn btn-primary" ng-disabled="!fileUploaded" ng-click="uploadFile()">Submit</button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM