angularjs - 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>
我总是从其他部分收到警报消息,这些消息表明无效
解决方案
您在 ng-click 方法中将表单作为字符串传递,而不是表单对象。所以您必须在没有 Single-cotts 的情况下传递表单对象。
ng-click="sm.submitForm('sampleForm')" to ng-click="sm.submitForm(sampleForm)"
推荐阅读
- eclipse - JavaFX 和 Apple M1(硅)芯片和 Eclipse 的问题
- java - 试图在有空格的字母数字字符串中找到所有数字的总和(即“my12 23name 14 is bijay”)
- javascript - 尝试制作一个用于创建帐户的 javascript 程序
- firebase - 属性“OnPress”未定义错误 - vue native & firebase
- postgresql - Postgres 逻辑复制,插槽和订阅者之间的关系
- python - 从另一个目录导入 Python 文件引发 ModuleNotFoundError
- javascript - 如何将类添加到使用 v-for 循环创建的特定元素?
- ruby-on-rails - Rails / Arel:选择案例总和以及模型
- java - 我应该在更新资源的同时使用 GET 还是 PATCH 来请求信息
- excel - 有没有办法从 Excel 中的列中聚合数据?