What is the replacement of jQuery's blur event in AngularJS?

Habibur Rahman picture Habibur Rahman · Jul 31, 2013 · Viewed 17.5k times · Source

I have to close any opened component when clicking outside of that component using angularjs. Is there an angular directive for blur events? If not, how can I do that?

Answer

Jesus Rodriguez picture Jesus Rodriguez · Jul 31, 2013

If you don't want to use angular-ui's ui-event, you can also create a small directive until the next version of Angularis released.

app.directive('ngBlur', function() {
  return function( scope, elem, attrs ) {
    elem.bind('blur', function() {
      scope.$apply(attrs.ngBlur);
    });
  };
});

Just put the directive where you need it:

<input type="text" ng-model="foo" ng-blur="doFoo()" />

Basically what the directive does is to bind the blur event of the element (in our example the input) and then when the event is fired (we leave the input) angular will apply what is in the directive. So in our case, doFoo() will be fired if we leave the input.

Plunker here: http://plunker.co/edit/J4ZEB6ppvkiIvdW9J2VU?p=preview