Angularjs自定义验证指令异步调用实时验证自定义、指令、实时、Angularjs

2023-09-10 22:16:43 作者:热情过期

我使用自定义的验证指令来验证一个表单字段和验证过程包括AJAX调用与服务器API验证用户信息。我们要验证的字段,只要用户停止输入为一定时间

I am using custom validation directive to validate a field in a form and the validation process includes a AJAX call to verify user information with server API. We want to validate the field as long as user stops typing for a certain period of time.

我有两个问题:

1.为什么低于不工作的功能?(在自定义指令链接功能)的日志信息从来没有表现出无论多少次我请在绑定输入字段(我pretty的肯定,我启用了日志消息显示,因为其他日志被correrctly所示)

1.Why is the function below not working?(with link function in the custom directive) The log message was never shown no matter how many times I type in the binded input field (I am pretty sure I enabled log message display since other logs were shown correrctly)

scope.$watch(attrs.ngModel, function() {
        $log.debug("Changed to " + scope.$eval(attrs.ngModel));  
});

2.什么是检测用户已停止输入的程序执行验证过程的最好方法是什么?而且它是可能的,如果用户开始再次键入它完成之前取消验证过程?

推荐答案

attrs.ngModel 将等于字符串值中的HTML内容。你想要做什么ngModel值绑定到该指令的适用范围:

attrs.ngModel will equal the string value in the html context. What you want to do is bind the ngModel value to the directive's scope:

scope: {
        model: '=ngModel'
    }

然后看指示范围:

Then watch the directives scope:

scope.$watch("model", function() {
       console.log("Changed"); 
    });

例如: http://jsfiddle.net/BtrZH/5/