簡體   English   中英

如何在angularjs中使用input [type = file]驗證表單

[英]How to validate form with input[type=file] in angularjs

HTML:

<form name="form">
    <input type="file" ng-model="document" valid-file required>
    <input type="submit" value="{{ !form.$valid && 'invalid' || 'valid' }}">
</form>

偵聽輸入[type = file]的自定義指令更改:

myApp.directive('validFile',function(){
    return {
        require:'ngModel',
        link:function(scope,el,attrs,ngModel){

            //change event is fired when file is selected
            el.bind('change',function(){
                 scope.$apply(function(){
                     ngModel.$setViewValue(el.val());
                     ngModel.$render();
                 });
            });
        }
    };
});

選擇文件后,控制台中出現以下錯誤:

錯誤:InvalidStateError:DOM異常11錯誤:嘗試使用不可用或不再可用的對象。

嘗試使用plunkr: http ://plnkr.co/edit/C5j5e0JyMjt9vUopLDHc?p = preview

如果沒有指令,輸入文件字段的狀態將不會被推送到。$ valid。 任何想法為什么我得到這個錯誤以及如何解決這個問題?

來自NgModelController的引用。$ render()

在需要更新視圖時調用。 預計ng-model指令的用戶將實現此方法。

你需要實現$ render()來調用它。 你可以做這樣的事情

myApp.directive('validFile', function () {
    return {
        require: 'ngModel',
        link: function (scope, el, attrs, ngModel) {
            ngModel.$render = function () {
                ngModel.$setViewValue(el.val());
            };

            el.bind('change', function () {
                scope.$apply(function () {
                    ngModel.$render();
                });
            });
        }
    };
});

DEMO

更新到AngularJS 1.2.x后,代碼段看起來不再正常工作,文件輸入不會粘在選定的文件值上,使表單無法使用。 將指令更改回原始指令,並刪除ngModel.$render()它看起來像魅力:

.directive('validFile', function () {
  return {
    restrict: 'A',
    require: '?ngModel',
    link: function (scope, el, attrs, ngModel) {
      el.bind('change', function () {
        scope.$apply(function () {
          ngModel.$setViewValue(el.val());
        });
      });
    }
  };

暫無
暫無

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

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