Trapflag
Trapflag

Reputation: 11

Angularjs custom validation directive Async call real time validation

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?

Upvotes: 0

Views: 437

Answers (1)

tommybananas
tommybananas

Reputation: 5736

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/

Upvotes: 1

Related Questions