我是angular JS的新手,我创建了一个
的表单HTML
<div data-ng-controller="ReservationController"
<form class="form-horizontal" role="form">
<div class="form-group">
<div class="col-sm-10">
<label>Guest Name</label>
<input type="text" class="form-control" placeholder="" ng-model="res_guest_name" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<label>Phone</label>
<input type="phone" class="form-control" ng-model="res_member_phone">
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<label>FAX</label>
<input type="phone" class="form-control" ng-model="res_member_fax">
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<label>Email</label>
<input type="email" class="form-control" ng-model="res_member_email" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-8 col-sm-10">
<button type="submit" class="btn btn-success" ng-click="res_save()">Save Changes</button>
</div>
</div>
</form>
</div>
CONTROLLER
function ReservationController($scope, $http, $cookieStore,$location,$filter) {
$scope.res_save = function()
{
var save_res ="https://pbg.com/save_form.html?contactid="+conId+"&token="+token+"&id="+$scope.resId+"&page=edit&guest_name="+$scope.res_guest_name+"&phone="+$scope.res_member_phone+"&fax="+$scope.res_member_fax+"&email="+$scope.res_member_email;
$http.get(save_res).success(function(response) {
alert('success');
});
}
}
即使必填字段留空,我的表单仍会提交。它显示错误,然后提交。
答案 0 :(得分:7)
显然它会提交您未处理提交表格的表格。您只是管理错误: - )
使用ng-disabled="myForm.$invalid"
其中myForm
是表单上的name
字段
<form class="form-horizontal" name="myForm" role="form">
<button type="submit" class="btn btn-success" ng-disable="myForm.$invalid" ng-click="res_save()">Save Changes</button>
如果您不希望此按钮被禁用,则可以使用
<button type="submit" class="btn btn-success" ng-click="res_save(myForm.$valid)">Save Changes</button>
在控制器中
$scope.res_save = function(valid)
{
if(valid){
var save_res ="https://pbg.com/save_form.html?contactid="+conId+"&token="+token+"&id="+$scope.resId+"&page=edit&guest_name="+$scope.res_guest_name+"&phone="+$scope.res_member_phone+"&fax="+$scope.res_member_fax+"&email="+$scope.res_member_email;
$http.get(save_res).success(function(response) {
alert('success');
});
}
}
答案 1 :(得分:0)
在保存之前,您没有检查表单有效状态,当表单无效时,不要指望angular会神奇地停止保存。
答案 2 :(得分:0)
您应该查看ng-submit的文档。如果将res_save函数移动到表单上的ng-submit中(并删除了对提交输入的ng-click),它将针对必填字段进行验证,防止执行函数直到它们有效。