问题描述
我使用自定义验证指令来验证表单中的字段,验证过程包括 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.为什么下面的函数不起作用?(在自定义指令中带有链接函数)无论我在绑定的输入字段中输入多少次,日志消息都不会显示(我是很确定我启用了日志消息显示,因为其他日志显示正确)
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'
}
然后观察指令范围:
scope.$watch("model", function() {
console.log("Changed");
});
示例:http://jsfiddle.net/BtrZH/5/
这篇关于Angularjs 自定义验证指令异步调用实时验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!