2013-03-16 81 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; 
     } 
    } 
} 

如果表单中输入的元素是有效的,那么形式将是有效的。希望这可以帮助。