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

编程入门 行业动态 更新时间:2024-10-26 16:27:28
本文介绍了Angularjs 自定义验证指令异步调用实时验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我使用自定义验证指令来验证表单中的字段,验证过程包括 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/BtrZH/5/

这篇关于Angularjs 自定义验证指令异步调用实时验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-21 15:09:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1005267.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   指令   实时   Angularjs

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!