我刚刚开始使用 AngularJS,如果表单有任何无效字段,我希望禁用表单的提交按钮。
我有一个名为标题的字段。它要求 minlength 为 5。在加载表单时,AngularJS 提供的表单对象报告 $invalid: false
<div ng-controller="NewPinCtrl as newPin">
<form role="form" name="formNewPin">
<div>
<label>Title</label>
<input ng-model="newPin.pin.title" ng-minlength="5" ng-maxlength="140" type="text" name="title" value="" placeholder="Title" />
<ul ng-messages="formNewPin.title.$error" ng-if="formNewPin.title.$dirty">
<li ng-message="required">This is required</li>
<li ng-message="minlength">Should be longer than 5 characters</li>
<li ng-message="maxlength">Should be shorter than 140 characters</li>
</ul>
</div>
</form>
</div>
这是我的按钮:
<button ng-click="newPin.savePin()" ng-disabled="formNewPin.$pristine || formNewPin.$invalid" type="button">Submit</button>
好吧,我想,如果表单是 $pristine: true
,我就禁用按钮。这解决了我的“加载中”问题...但是当用户清除该字段并返回空白时,$invalid
报告为 false
。
为什么会这样,因为这个字段显然有最小长度要求?而且,如何在不单独检查每个表单字段错误的情况下绕过它?
谢谢!
编辑:我可能会补充一点,我在 1.3 中使用这个新的 ngMessages
最佳答案
您已提供所需错误的消息,但尚未将输入标记为必需。这就是为什么它在第一次加载时被评估为有效。
添加 required 属性后,您将不需要为 ng-messages 使用 ng-if。最终的解决方案应该是这样的:
<form name="formNewPin">
<label>Title</label>
<input ng-model="newPin.pin.title" required ng-minlength="5" ng-maxlength="140" type="text" name="title" value="" placeholder="Title">
<ul ng-messages="formNewPin.title.$error">
<li ng-message="required">This is required</li>
<li ng-message="minlength">Should be longer than 5 characters</li>
<li ng-message="maxlength">Should be shorter than 140 characters</li>
</ul>
<button ng-click="newPin.savePin()" ng-disabled="formNewPin.$invalid" type="button">Submit</button>
</form>
Plunker为此。
关于javascript - AngularJS 1.3 - 为什么表单在加载时有效,对于最小长度的输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26682196/