【问题标题】:Angular JS HTML5 ValidationAngular JS HTML5 验证
【发布时间】:2013-03-05 12:40:08
【问题描述】:

我有一个表单,我在输入中使用了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>

【问题讨论】:

    标签: html forms validation angularjs


    【解决方案1】:

    如果您为表单命名,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;
            }
        }
    }
    

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

    【讨论】:

      猜你喜欢
      • 2017-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-02
      • 2023-04-07
      • 1970-01-01
      • 2013-07-08
      相关资源
      最近更新 更多