2013-03-16 159 views
4

我有一個表單,我在輸入上使用了required tag - 這工作正常,但在提交按鈕上我有ng-click="visible = false",當數據提交時隱藏表單。Angular JS HTML5驗證

我該如何使它只有在所有驗證都正確的情況下設置爲false?

App.js

$scope.newBirthday = function(){ 

     $scope.bdays.push({name:$scope.bdayname, date:$scope.bdaydate}); 

     $scope.bdayname = ''; 
     $scope.bdaydate = ''; 

    }; 

HTML:

<form name="birthdayAdd" ng-show="visible" ng-submit="newBirthday()"> 
     <label>Name:</label> 
     <input type="text" ng-model="bdayname" required/> 
     <label>Date:</label> 
     <input type="date" ng-model="bdaydate" required/> 
     <br/> 
     <button class="btn" ng-click="visible = false" type="submit">Save</button> 
     </form> 

回答

4

如果你給一個名字形式的FormController將其名稱最接近的控制範圍被曝光。所以你的情況說你有一個結構類似

<div ng-controller="MyController"> 
    <!-- more stuff here perhaps --> 
    <form name="birthdayAdd" ng-show="visible" ng-submit="newBirthday()"> 
     <label>Name:</label> 
     <input type="text" ng-model="bdayname" required/> 
     <label>Date:</label> 
     <input type="date" ng-model="bdaydate" required/> 
     <br/> 
     <button class="btn" ng-click="onSave()" type="submit">Save</button> 
     </form> 
</div> 

現在在你的控制器

function MyController($scope){ 
    // the form controller is now accessible as $scope.birthdayAdd 

    $scope.onSave = function(){ 
     if($scope.birthdayAdd.$valid){ 
      $scope.visible = false; 
     } 
    } 
} 

如果表單中輸入的元素是有效的,那麼形式將是有效的。希望這可以幫助。