Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 875
Habibur Rahman Avatar asked Jul 31 '13 07:07

Habibur Rahman


People also ask

What is Ng blur in AngularJS?

The ng-blur directive tells AngularJS what to do when an HTML element loses focus. The ng-blur directive from AngularJS will not override the element's original onblur event, both the ng-blur expression and the original onblur event will be executed.

What is blur function in angular?

A blur event fires when an element has lost focus. Note: As the blur event is executed synchronously also during DOM manipulations (e.g. removing a focussed input), AngularJS executes the expression using scope. $evalAsync if the event is fired during an $apply to ensure a consistent state.

What is blur () method?

blur() method removes keyboard focus from the current element.


1 Answers

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

like image 171
Jesus Rodriguez Avatar answered Sep 22 '22 08:09

Jesus Rodriguez