我有一个有角度的应用程序,其中包含一个取自示例的保存按钮:
<button ng-click="save" ng-disabled="form.$invalid">SAVE</button>
这对于客户端验证非常有用,因为form.$invalid
当用户修复问题时变为 false,但我有一个电子邮件字段,如果另一个用户使用同一电子邮件注册,该字段将设置为无效。
一旦我将电子邮件字段设置为无效,我就无法提交表单,并且用户无法修复该验证错误。所以现在我不能再使用form.$invalid
禁用我的提交按钮。
一定会有更好的办法
这是自定义指令成为您朋友的另一种情况。您需要创建一个指令并将 $http 或 $resource 注入其中,以便在验证时回调服务器。
自定义指令的一些伪代码:
app.directive('uniqueEmail', function($http) {
var toId;
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attr, ctrl) {
//when the scope changes, check the email.
scope.$watch(attr.ngModel, function(value) {
// if there was a previous attempt, stop it.
if(toId) clearTimeout(toId);
// start a new attempt with a delay to keep it from
// getting too "chatty".
toId = setTimeout(function(){
// call to some API that returns { isValid: true } or { isValid: false }
$http.get('/Is/My/EmailValid?email=' + value).success(function(data) {
//set the validity of the field
ctrl.$setValidity('uniqueEmail', data.isValid);
});
}, 200);
})
}
}
});
以下是在标记中使用它的方法:
<input type="email" ng-model="userEmail" name="userEmail" required unique-email/>
<span ng-show="myFormName.userEmail.$error.uniqueEmail">Email is not unique.</span>
编辑:对上面发生的事情的一个小解释。
- 当您更新输入中的值时,它会更新 $scope.userEmail
- The directive has a $watch on $scope.userEmail it set up in it's linking function.
- 当 $watch 被触发时,它会通过 $http ajax 调用来调用服务器,并传递电子邮件
- 服务器将检查电子邮件地址并返回一个简单的响应,例如 '{ isValid: true }
- 该响应用于控件的 $setValidity 。
- 标记中有一个 ng-show 设置为仅在 uniqueEmail 有效性状态为 false 时显示。
...对于用户来说这意味着:
- 输入电子邮件。
- 轻微的停顿。
- 如果电子邮件不唯一,“电子邮件不唯一”消息将显示“实时”。
EDIT2:这也允许您使用 form.$invalid 禁用提交按钮。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)