简体   繁体   English

回调函数内的角形验证 - 角度1.2.5

[英]angular form validation inside callback function - angular 1.2.5

I'm working an application with indexedDb as storage. 我正在使用indexedDb作为存储的应用程序。 In one of the forms while checking for the existence of a key I'm facing a strange error. 在检查是否存在密钥时,其中一种形式我面临一个奇怪的错误。 Below is my validation directive code 下面是我的验证指令代码

app.directive('ensureUnique',['abcService', function ($abcService){
return {
    require : 'ngModel',
    link : function(scope,elem,attr,ctrl) {
        scope.$watch(attr.ngModel, function(){
             var checkExpenseType = $abcService.checkExpenseType();
             var index = checkExpenseType.get(scope.newExpenseName );
             index.onsuccess = function (e) {
                var result = e.target.result;
                if(result) {
                    ctrl.$setValidity('exists', true);
                 }else{
                    ctrl.$setValidity('exists', false);
                 }
             };
             index.onerror = function(e) {
                // TODO
             };   
        });
    }, 
  }}
]);

While entering input text if the value matches the key in db for the first time proper error message is displayed. 输入文本时,如果值第一次与db中的键匹配,则会显示正确的错误消息。 Upon next key press error vanishes which is the correct behavior but for subsequent keypresses error reappears even though key is not present in DB. 在下一次按键错误消失时,这是正确的行为,但对于后续按键错误,即使DB中没有按键,也会再次出现错误。

 For example if "Food"  is the key in DB
 Foo - No error
 Food - Error - Key exists
 Foods - No error
 Foodss - Error - key exists
 Foodsss - Error - key exists
 ...       

Since there is a min length criteria of 3 characters directive is not triggered till I enter 3 characters. 由于存在3个字符的最小长度标准,因此在我输入3个字符之前不会触发指令。

Please also let me know if I'm doing the validation in the intended way or a better way exists 如果我以预期的方式进行验证或存在更好的方法,也请告诉我

Thanks in advance 提前致谢

I've forked your Fiddle and made some changes. 我已经分叉你的小提琴并做了一些改变。 http://jsfiddle.net/U9y3H/1 . http://jsfiddle.net/U9y3H/1

Firstly I've added a scope.$apply() since your validation is happening asynchronously and therfore outside of angular's digest cycle. 首先,我添加了一个范围。$ apply(),因为您的验证是异步发生的,因此在angular的摘要周期之外。

Secondly I've swapped $setValidity to false if a match is found, and true if a match isn't found. 其次,如果找到匹配项,我将$ setValidity交换为false,如果找不到匹配项,则为true。 I believe this to be correct if you want to invalidate the field if an entry already exists. 如果您想在条目已经存在的情况下使字段无效,我认为这是正确的。

if(result) {
    // If a match is found, mark the field as invalid.
    ctrl.$setValidity('exists', false); 
}else{
    // If a match is not found mark "exists" as valid.
    ctrl.$setValidity('exists', true);
}
// Apply the validation changes.
scope.$apply();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM