使用AngularJS,如果未选中复选框,如何在单击提交按钮后显示复选框的错误消息?
我试过了:
<form action="/" method="post" name="myForm" novalidate>
<label>
<input type="checkbox" name="myCheckbox" ng-model="myCheckbox" value="1" required>
</label>
<p class="error" ng-show="myForm.$submitted && myForm.myCheckbox.$error.required">Error message</p>
<button type="submit" ng-disabled="myForm.$invalid">Submit</button>
</form>
但它没有用。当我点击提交按钮时,什么也没发生。如果我在表单标签上删除“novalidate”或在提交按钮上删除“ng-disabled”,即使未选中该复选框,也会提交表单。
你能帮我吗?
答案 0 :(得分:1)
您的提交按钮中有ng-disabled="myForm.$invalid"
,因此提交事件永远不会被触发(因为当表单无效时按钮被禁用)因此条件ng-show="myForm.$submitted && myForm.myCheckbox.$error.required"
永远不会被满足,因为{{1是假的。
修改强>
正如其他一些用户所建议的那样,我认为最好的办法就是改变你现在做事的方式。我可以想到两个解决方案(非常相似),但它们包括发送请求“角度方式”
使用这样的角度处理表单提交:
将表单添加到您的表单中(请注意,我删除了myForm.$submitted
部分:
action="/" method="post"
并从提交按钮中删除<form ng-submit="onSubmit(myForm)" name="myForm" novalidate>
。那就像这个ng-disabled="myForm.$invalid"
......并在控制器中
<button type="submit">Submit</button>
同样改变这样的形式:$scope.onSubmit = function(form){
if(form.$invalid){
//... do your call to backend here as you like since the call directly from the form was removed
}
}
...更改您的提交按钮,如下所示:<form name="myForm" novalidate>
...并使用控制器中声明的相同函数
<button type="submit" ng-click="onSubmit(myForm)">Submit</button>
否则你必须像这样改变你的状况
$scope.onSubmit = function(form){
if(form.$invalid){
//... do your call to backend here as you like since the call directly from the form was removed
}
}
但这会在提交表单之前显示消息
答案 1 :(得分:0)
删除myForm.$submitted
,因为它永远不会被履行(正如Asiel Leal所提到的那样),并且您已将ng-disabled
置于提交按钮上,因此可以安全使用。
<form action="/" method="post" name="myForm" novalidate>
<label>
<input type="checkbox" name="myCheckbox" ng-model="myCheckbox" value="1" required>
</label>
<p class="error" ng-show="myForm.$dirty && myForm.myCheckbox.$error.required">Error message</p>
<button type="submit" ng-disabled="myForm.$invalid">Submit</button>
</form>
答案 2 :(得分:0)
试试这个有效的例子:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app= "myApp" ng-controller="myController">
<form name="myForm" ng-submit="myForm.$valid && validate()" novalidate>
<input type="checkbox" name="checkb" ng-model="formData.checkb" required/>
<span ng-show="submitted == true && myForm.checkb.$error.required">Please select the checkbox to proceed.</span>
<input type="submit" value="Submit" ng-click="submitted = true"/>
</form>
</div>
&#13;
as.Date('2016-12-22') - as.Date('0000-01-01') # 1st day of year 0
# Time difference of 736685 days
&#13;