Thursday, September 27, 2012

AngularJS: Notification Callback on Blur Event

This is one of those things in AngularJS that is perhaps a bit more complicated than it really should be, as the only way I know to do this at the moment is via a Directive. AngularJS updates the model instantly when it changes. In the case of the text input field, it's after every character is typed or deleted. However, there are times where you want to be notified only on the "blur" event, such as when calling the server to validate the value.

   directive('input', function() {
       return {
           restrict: 'E',
           link: function(scope, element, attr) {

               if (attr.type === 'radio' || attr.type === 'checkbox') return;

               element.bind('blur', function() {
                   scope.$apply(function() {
                    scope.onBlur(element.attr("name"));
                   });
               });
           }
       }
   });

In this example, the Controller's "onBlur" callback is called with the element's name. This example returns immediately if the input is of type "radio" or "checkbox", because the "change" event is  more applicable for them.

1 comment:

  1. Nice post. For one more useful directive for blur event see this post
    http://coding-issues.blogspot.in/2013/10/angularjs-blur-directive.html

    ReplyDelete