2017-01-12 141 views
0

我有一個表單,其中有一個必填字段和一個非必填字段。在成功提交表單發送數據到服務器後,我將清除兩個輸入字段模型中的數據。但是通過這樣做,所需字段將變爲紅色並顯示錯誤This field is required。在提交表格並清除其數據後,如何保持必填字段的錯誤。我希望它僅在用戶嘗試使用EMPTY REQUIRED FIELD提交表單時才顯示錯誤。提交時出現錯誤

<form name="myForm"> 
    <div layout="row" layout-align="center center" flex="100"> 
     <md-input-container class="md-block" flex="40"> 
      <input required type="text" placeholder="Book Name" 
        ng-model="bookName" 
      /> 

      <div ng-messages="$error"> 
       <div ng-message="required">This is required.</div> 
      </div> 
     </md-input-container> 

     <span flex="10"></span> 

     <md-input-container class="md-block" flex="40"> 
      <input type="text" placeholder="Theme" 
        ng-model="theme" 
        enter-pressed=""/> 
     </md-input-container> 
    </div> 
</form> 

<md-button class="md-raised md-primary" flex="none" type="submit" 
      ng-click="onSubmitClicked()">Submit 
</md-button> 


    $scope.onSubmitClicked = function() { 
     $scope.bookName = ""; // this causes the REQUIRED FIELD ERROR AFTER I SUBMIT THE FORM 
     $scope.theme = ""; 
    }; 

回答

0

你應該改變你的onSubmitClicked這樣

$scope.onSubmitClicked = function(form) { 
     $scope.bookName = ""; // this causes the REQUIRED FIELD ERROR AFTER I SUBMIT THE FORM 
     $scope.theme = ""; 

     if(form){ //make sure a form is passed as parameter 
     form.$setPristine(); //this will reset the form to its original state 
     } 
    }; 

像這樣

... 
<md-button class="md-raised md-primary" flex="none" type="submit" 
      ng-click="onSubmitClicked(myForm)">Submit 
</md-button> 
... 
+0

仍然顯示錯誤 – user2498079

+1

@ user2498079,這將是巨大的,如果你能以重現錯誤,並幫助您做出剪斷,一個的jsfiddle或對我們類似的東西爲此尋找解決方案。 – lealceldeiro

0

添加到亞薛的回答調用此功能,您應該清除模型後請執行下列操作。

    if(form){ //make sure a form is passed as parameter 
        form.$setPristine(); //this will reset the form to its original state 
        form.$setUntouched(); 
       } 

form.$setUntouched會將窗體設置爲未觸摸狀態,從而刪除錯誤消息。

0

,請執行以下操作:

<form name="myForm" ng-submit="onSubmitClicked(myForm)"> 

    <md-button class="md-raised md-primary" flex="none" type="submit">Submit</md-button> 
</form> 


$scope.onSubmitClicked = function(form) { 
    if (form.$valid) { 
      // do what you have to do, the form is validated 
     return; 
    } 

    // dont do anythign the form will flag ans $invalid and $submitted and the error messages will show 
    return; 

}; 
相關問題