我正在 Angular 中创建一个包含三个输入的注册表单:email
、password
和 passwordConfirm
。我的 Controller 看起来像这样:
app.controller('SignupController', function ($scope, User) {
$scope.user = {};
$scope.signup = function() {
User.save($scope.user, function(success) {
// TODO
}, function(error) {
if (error.status === 422) {
error.data.errors.forEach(function(item) {
$scope.signupForm[item.field].$setValidity(item.error, false);
});
}
});
};
});
这是在用户提交表单注册时向我的 API 发送请求。如果返回 422
响应(这意味着验证错误),我将遍历它们并根据 API 返回的内容将相应的输入设置为无效。
让我们以已经注册的电子邮件地址为例。我在我的 View 中显示验证错误是这样的:
<small class="error" ng-show="signupForm.email.$error.exists">Email address taken, please use another</small>
这一切都完美无缺,但我的用户现在卡住了,因为当他们尝试将电子邮件地址更改为另一个地址时,email
字段的有效性并未更改以允许他们重新提交表单(我根据表单有效性禁用提交按钮)。
基本上,我需要在用户更改输入模型后将验证属性(在本例中为 exists
)重置为 true
。对我来说最好的方法是什么?
编辑 发帖后突然灵机一动,我将其添加到我的 Controller 中:
$scope.$watch('user.email', function() {
// Reset exists validation property back to true
$scope.signupForm.email.$setValidity('exists', true);
});
这似乎有效。当用户在输入设置为无效后更改模型值时,这会将其设置回有效。但这并不是执行此操作的最佳方法。有人知道吗?
最佳答案
我也曾被这个问题困扰过。阅读您的帖子后,我想出了一个可能的解决方案 - 创建一个指令,该指令正在监视模型的更改并重置更改时的有效性状态(基本上是您建议的,但放在通用指令中)
angular.module('app').directive('resetValidityOnChange', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, iElem, iAttrs, ngModelCtrl) {
ngModelCtrl.$viewChangeListeners.push(function () {
ngModelCtrl.$setValidity(iAttrs['resetValidityOnChange'], true);
});
}
}
}
您必须将此指令添加到您想要重置的输入中,例如:
<input type="text" ng-model="vm.email" reset-validity-on-change="exists" />
关于javascript - 在模型更改后切换 $setValidity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29337121/