首页 > 解决方案 > Angularjs 1 表单验证问题

问题描述

我在我的项目中使用 Angularjs 1。我正在验证 Angular 中的表单,所以我使用form.$valid来检查提交的表单是否有效,但它不能正常工作,不确定我错过了什么

<!DOCTYPE html>
<html ng-app="myApp">
  <head>
     <meta charset="utf-8" />
     <title> Learning AngularJS Filters </title>
     <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.2/angular.min.js"></script>
     <script>
         "use strict";
         angular.module("myApp",[]);
         angular.module("myApp").controller("SampleController",[function(){
               this.user = {}
               this.submitForm = function(form){
                    if(form.$valid){
                        window.alert("Valid")
                    }else{
                        window.alert("In Valid");
                    }
               }
         }]);
     </script>
  </head>
  <body>
     <div ng-controller="SampleController as sm" class="container">
        <form name="sampleForm" novalidate>
            <div class="form-group">
                <label for="exampleInputEmail1"> Username </label>
                <input type="text" class="form-control" ng-model="sm.user.name" id="exampleInputEmail1"  placeholder="Enter Username" required>
            </div>
            <div class="form-group">
                <label for="exampleInputPassword1">Password</label>
                <input type="password" class="form-control" ng-model="sm.user.pwd" id="exampleInputPassword1" placeholder="Password" required>
            </div>
            <button type="submit" ng-click="sm.submitForm('sampleForm')" class="btn btn-primary">Submit</button>
            <p> {{ sm.user }} </p>
        </form>
     </div> <!--/ container -->
  </body>
</html>

我总是从其他部分收到警报消息,这些消息表明无效

标签: angularjsangular1.6

解决方案


您在 ng-click 方法中将表单作为字符串传递,而不是表单对象。所以您必须在没有 Single-cotts 的情况下传递表单对象。

 ng-click="sm.submitForm('sampleForm')" to ng-click="sm.submitForm(sampleForm)"

推荐阅读