簡體   English   中英

當字段為空時,必需的指令返回false。 但是當我管理表單對象時,它顯示要求是真的為什么?

[英]required directive return false, when field is empty. but when i console the form object it shows required is true why?

創建的插件我有以下html代碼:

<form name="form1">
    <input type="text" ng-model="mk" required/>
    <input type="submit" placeholder="submit" ng-click="submitIt(form1)" >
</form>

控制器:

$scope.submitIt=function(form1){
    console.log(form1);
}

當我提交沒有任何值的表單(空字段),並在console.in中看到時,它顯示required:true 但根據必需的指令,它返回required : false

angular.js庫提供的必需指令:

var requiredDirective = function() {
  return {
    require: '?ngModel',
    link: function(scope, elm, attr, ctrl) {
      if (!ctrl) return;
      attr.required = true; // force truthy in case we are on non input element

      var validator = function(value) {
        if (attr.required && ctrl.$isEmpty(value)) {
          ctrl.$setValidity('required', false);
          return;
        } else {
          ctrl.$setValidity('required', true);
          return value;
        }
      };

      ctrl.$formatters.push(validator);
      ctrl.$parsers.unshift(validator);

      attr.$observe('required', function() {
        validator(ctrl.$viewValue);
      });
    }
  };
};

我很困惑,為什么會這樣。

如果required為true,並且沒有輸入,則有效性為false。

您在指令中看到的錯誤是為了確保有效性

   ctrl.$setValidity('required', false);

它將有效性設置為false,這意味着如果需要輸入且未提供任何輸入,則該字段處於無效狀態...

在bitton上使用ng-disabled以防止提交表單。

    <input type="submit" placeholder="submit" ng-click="submitIt(form1)" ng-disabled="form1.$invalid || !form1.$dirty">

這里

暫無
暫無

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

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