1

I am trying to validate my email address for uniqueness.

With a traditional method, what happens is on every key press the $http service is being called and lots of database calls are being fired because of this. I want to make it an on blur event.

I wrote a script and it's working fine but when I test it for the blur event it still fires the $http service several times. By several times; let's suppose the ajax call already fires for the first time, upon the next go 2 calls will be caught in firebug, and this happens again for the next go making a total of 3 extra calls. This makes 6 calls for every 3.

elem.unbind('input').unbind('keydown').unbind('change');
   elem.on('blur', function(){                  
       bindData();
       scope.$apply(function () {
         ctrl.$setViewValue(elem.val());
       });
   });

The plunker of the code is here.

http://plnkr.co/edit/kR9v91nV2uTkuTtwgX6p?p=preview

Matt
  • 1,013
  • 8
  • 16
kishor10d
  • 543
  • 6
  • 24

1 Answers1

1

This part of the code in your example

elem.unbind('input').unbind('keydown').unbind('change');
            elem.on('blur', function(){
              // on blur ajax call will fire
                bindData();
                scope.$apply(function () {
                          ctrl.$setViewValue(elem.val());
                    });
            });

seems to show that you're writing AngularJS code in jQuery way. This is not how it's designed to be used, please take a look at this remarkable post - "Thinking in AngularJS" if I have a jQuery background?.

For your case main requirement - to decrease amount of server calls by debouncing model changes - there is a specific AngularJS model property ngModelOptions. Utilizing this your <input> tag code will look like this:

<input ng-model-options="{ updateOn: 'default blur', debounce: { 'default': 500, 'blur': 0 } } /*other attributes*/ />
Community
  • 1
  • 1
shershen
  • 9,875
  • 11
  • 39
  • 60