单击“提交”按钮后,表单将被提交,而不是验证必填字段。
标记
<!DOCTYPE html>
<html lang="en" ng-app="myApp" ng-controller="myCtrl">
<head>
<meta charset="UTF-8">
<title>HTML 5</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
</head>
<body>
<div id="container">
<p ng-show="msg"> {{ msg }}</p>
<form name="myForm" novalidate ng-submit="valid()">
<p> Name <input type="text" name="name" id="" ng-model="user.name" ng-required=true></p>
<p ng-show="myForm.name.$invalid && myForm.name.$touched">name is required</p>
<p> Email <input type="email" name="email" id="" ng-model="user.email" ng-required=true> </p>
<p ng-show="myForm.email.$invalid && myForm.email.$touched">must be a valid email</p>
<input type="submit" value="submit">
</form>
</div>
<script>
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope) {
$scope.valid = function() {
$scope.msg = "form submitted";
}
}]);
</script>
</body>
</html>
任何帮助都会受到赞赏。感谢
答案 0 :(得分:1)
如果表单是有效的,则调用函数的最短方式如下所示,仅当表单有效时才会激活有效function
。
ng-submit="myForm.$valid && valid()"
或者其他方式是检查myForm
中的$scope
对象,因为当您在表单上提供name="myForm"
时,angular会在范围内创建一个对象,其中包含所有信息字段信息对象
$scope.valid = function(){
if($scope.myForm.$valid){
//form is valid
//do $http.post call if you wanted to submit form data
}
else {
alert('form is invalid');//some how notify user that form is invalid.
}
}
答案 1 :(得分:0)
尝试放置:
$scope.valid=function() {
if ($scope.myForm.isValid()) $scope.msg="form submitted";
else $scope.msg="form with errors";
}
希望有所帮助
答案 2 :(得分:0)
您可以使用以下命令禁用提交按钮:
ng-disabled="boolean expression"
在你的情况下,它将是简单的:
<input type="submit" value="submit" ng-disabled="!myForm.$valid">