[英]AngularJS: Required form field not woking with ng-click submit
<div ng-app>
<div ng-controller="Ctrl">
<form ng-submit="submit() ">
<textarea ng-model="text" required></textarea>
<div ng-click="submit()" style="background-color:#ff00ff;cursor:pointer;width:100px;">Create !</div>
<button type="submit" style="background-color:#ff00ff;cursor:pointer;width:100px;">Create !</button>
</form>
{{list}}
</div>
</div>
I want to submit an Angular form with a custom div button but when I do it like above, the "required" statements are not taken into account like it is done for the button . 我想提交一个带有自定义div按钮的Angular表单,但是当我像上面那样执行时,“required”语句不会像按钮那样被考虑在内。
When the textarea is empty the first button runs the submit() function anyway. 当textarea为空时,第一个按钮仍会运行submit()函数。 Is it possible to have the same behavior as the button ?
是否可以与按钮具有相同的行为?
Here is a JsFiddle illustrating this: http://jsfiddle.net/xKkvj/55/ 这是一个说明这个的JsFiddle: http : //jsfiddle.net/xKkvj/55/
I think you should be using an input
rather than a div
, eg: 我认为你应该使用
input
而不是div
,例如:
<input type="submit" ng-click="submit()" style="background-color:#ff00ff;cursor:pointer;width:100px;">Create !</input>
I've tested it on your jsFiddle, and it works fine. 我已经在你的jsFiddle上测试了它,它运行正常。
If you really must use a <div>
, use it to wrap the <input>
如果你真的必须使用
<div>
,用它来包装<input>
UPDATE UPDATE
It looks like you can't use anything other than an input
or a button
as that is what ngForm
listens to for form submission. 看起来你不能使用除
input
或button
以外的任何东西,因为这是ngForm
监听表单提交的内容。 You could either extend ngForm
or you could use a hidden button and trigger that from your div like so: 您可以扩展
ngForm
,也可以使用隐藏按钮并从div中触发,如下所示:
<div onClick="document.getElementById('hiddenButton').click();" style="background-color:#0000ff;cursor:pointer;width:100px;">Create !</div>
<button id='hiddenButton' type="submit" style="display:none;">Create !</button>
jsFiddle here . jsFiddle 在这里 。 Hopefully this'll do the trick for you.
希望这对你有所帮助。
If you want to submit form from a div
element, then you should manually test if form is valid in your submit
handler: 如果要从
div
元素提交表单,则应手动测试表单在submit
处理程序中是否有效:
function sumbit() {
if (form.$invalid) {
return;
}
// Other code...
}
The point is that when you submit your form via <input type="submit"/>
, then form validation check is performed internally & form handler do not invoked in case of invalid form. 关键是当您通过
<input type="submit"/>
表单时,表单内部执行表单验证检查,并且在表单无效的情况下不会调用表单处理程序。
UPDATE UPDATE
Your jsfiddle form handler should look like: 您的jsfiddle表单处理程序应如下所示:
$scope.submit = function () {
if ($scope.submitCreateSurveyForm.$invalid) {
return;
}
if ($scope.text) {
$scope.list.push($scope.text);
$scope.text = '';
}
console.log("sent");
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.