AngularJS-防止提交带有必填字段的表单

AngularJS-防止提交带有必填字段的表单

问题描述:

我有一个AngularJS表单,其中包含3个必填字段(使用ng-required).在不触摸表单上任何内容的情况下,只需简单地按下提交"按钮(ng-click ="submit"),我如何触发对必填字段的确认 AND 即可阻止表单提交?我试着做:

I have an AngularJS Form with 3 required fields inside (using ng-required). Without touching anything on the form and just simply pressing the 'Submit' button (ng-click="submit"), how do I trigger validation for the required fields AND prevent form submission? I've tried doing:

ng-required="form.$submitted && !firstName"

这会触发验证,但即使表单在技术上是$ invalid,也要提交表单?

which triggers the validation, but also submits the form even though the form is technically $invalid??

我使用了 ng-submit 指令,因为它触发了 form.$ submitted 并验证了 ng必填字段,然后再提交.

I used the ng-submit directive as it triggers form.$submitted and validates ng-required fields properly before submitting.

对于有多个按钮的情况,因为我向每个按钮添加了ng-click并仅更改了$ scope变量(例如$ scope.pressedBtn).在ng-submit指向的函数中,您可以执行以下操作:

For the case where you have multiple buttons, for I added an ng-click to each button and simply changed a $scope variable (e.g. $scope.pressedBtn). In the function that ng-submit points to, you could do something like:

if ($scope.pressedBtn === 'button1') {
    // submit
}
else if ($scope.pressedBtn === 'button2') {
    // save
}