2014-10-02 82 views
0

我正在研究一個角度表單,這是我第一次使用Angular Form。我能夠成功提交表單。但我想做2件事:在AngularJs中驗證後隱藏表格

  1. 驗證表單。
  2. 如果有效,請隱藏表格,並在確認後顯示div

現在我們可以使用ng-click隱藏表格& ng-hide表單的屬性。但我希望這個隱藏基於驗證發生。我期待驗證電子郵件,最小&最大長度&需要。

形式代碼:

<form id="signup-form" ng-submit="processForm()" ng-hide="showConfirm" > 
    <div class="col-md-12"><h4 class="col-md-12" >What do you think?</h4></div> 
    <div class="form-group col-md-12"> 
    <div class="row"> 
     <div class="radio col-md-6"> 
      <label> 
       <input type="checkbox" ng-model="formData.option1" > 
       Option1 
      </label> 
     </div> 

     <div class="radio col-md-6"> 
      <label> 
       <input type="checkbox" ng-model="formData.option2" > 
       Option2 
      </label> 
     </div> 
     </div>  
    </div> 
<div class="col-md-12 contact"> 
    <h4 class="col-md-12" >Want us to contact you?</h4> 
    <div class="form-group"> 
     <div class="textbox col-md-12"> 
      <label>Name </label> 
       <input type="text" ng-model="formData.name" > 

     </div> 
     <div class="textbox col-md-12"> 
      <label>Email </label> 
       <input type="text" ng-model="formData.email" > 

     </div> 
     <div class="textbox col-md-12"> 
      <label>Phone </label> 
       <input type="text" ng-model="formData.phone" > 

     </div> 
    </div>  
    </div> 
    <div class="form-group row"> 
    <div class="col-md-12 "> 
     <div class="col-md-12 contact"> 
      <button type="submit" class="btn btn-primary" ng-click="showConfirm = ! showConfirm">Submit</button> 
     </div> 
    </div> 
    </div> 
</form> 
<div class="col-md-12 confirmation" ng-show="showConfirm"> 
    <h2 >Thanks alot for your feedback.</h1> 
</div> 

JS代碼:

$scope.processForm = function() {        
    $http.post('http://localhost/api/node.json', $scope.formData) 
     .success(function(data) {    
      $scope.formData = {};     
      $state.go('main.start');  
     });   
}; 

回答

2

給您的表單的名稱和NG-提交,檢查表格的有效性與$有效的財產。

<form id="signup-form" name="signUpForm" novalidate ng-submit="signUpForm.$valid && processForm()" ng-hide="showConfirm"> 

將驗證屬性添加到您的輸入。例如:

<input type="text" ng-model="formData.email" required> 

然後,一旦提交表單,該showConfirm屬性設置爲true

瞭解更多關於驗證此類似以下應該工作https://docs.angularjs.org/guide/formshttp://www.ng-newsletter.com/posts/validations.html

1

東西。

HTML

<form name="signup-form" class="signup-form" novalidate method="post" ng-submit="processForm()" ng-hide="!signup-form.$invalid" ng-show="signup-form.$invalid" > 
    <div class="form-group"> 
    <label>Name</label> 
    <input type="text" class="form-control input-lg" name="username" placeholder="Username" ng-model="user.username" ng-required="true"> 

    <label>Email</label> 
    <input type="email" class="form-control input-lg" name="email" placeholder="Email" ng-model="user.email" ng-maxlength="20" ng-minlength="10" ng-required="true"> 
    </div> 
</form> 

<div ng-hide="!signup-form.$invalid" ng-show="signup-form.$invalid"> 
</div>