Angular JS HTML5验证

时间:2013-03-16 22:28:18

标签: html5 forms validation angularjs

我有一个表单,我在输入中使用了required tag - 这很好但在我的提交按钮上我有ng-click="visible = false"在提交数据时隐藏表单。

如果所有验证都正确,我该如何才能将其设置为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>

1 个答案:

答案 0 :(得分: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;
        }
    }
}

如果表单内的输入元素有效,则表单有效。希望这可以帮助。