Angularjs custom validation directive Async call real time validation

不问归期 提交于 2019-12-25 06:05:07

问题


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.

I have two questions:

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.What is the best way to detect that the user has stopped typing for the program to execute the validation process? And is it possible to cancel the validation process before it is finished if user starts to type again?


回答1:


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"); 
    });

example: http://jsfiddle.net/BtrZH/5/



来源:https://stackoverflow.com/questions/24946822/angularjs-custom-validation-directive-async-call-real-time-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!