【问题标题】:Clear angular form validation after correcting entry by updating $scope model通过更新 $scope 模型更正条目后清除角度表单验证
【发布时间】:2014-09-23 05:36:43
【问题描述】:

因此我有一个字段:

<input type="text" class="form-control" name="username" ng-model="user.username" ng-minlength="3" ng-maxlength="20" required ng change="checkUsername()">
<p ng-show="username_taken"  class="help-block">This username is taken.  
<a href="javascript:void(0);" ng-click="suggestUsername()">Shall we suggest one?</a></p>

用户点击Shall weSuggest?后,会调用suggestUsername()函数并用唯一的用户名填充用户名($scope.user.username),这会更新模型,但表单验证$valid状态为未清除。

我如何告诉 Angular 在我更新其模型后重新验证表单?

感谢您的帮助!

【问题讨论】:

  • form.$setPristine 将表单设置为其初始未验证状态,试试看。
  • 谢谢 - 由于某种原因不起作用。 $scope.userSignup.$setValidity(); $scope.userSignup.$setPristine();

标签: javascript angularjs


【解决方案1】:

调用 $setPristine() 到表单

https://docs.angularjs.org/api/ng/type/form.FormController

例子:

你的html:

<form name="yourFormName" id="form" novalidate>
   <!-- your form controls here -->
</form>

你的控制器:

// set to pristine, ONLY clears CSS styling, etc...
$scope.yourFormName.$setPristine();

// update your model values as well

【讨论】:

  • 谢谢 - 由于某种原因不起作用。 $scope.userSignup.$setValidity(); $scope.userSignup.$setPristine();
  • 你的意思是,表单输入控件样式还是提示表单无效?
  • 一旦我在 $scope 中声明了我的表单模型,它就起作用了。 ng-min 导致模型对象在满足其条件之前不会被实例化,我猜我在测试中没有处理。
猜你喜欢
  • 2020-12-22
  • 2015-04-30
  • 2014-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-18
  • 1970-01-01
相关资源
最近更新 更多