Habibur Rahman
Habibur Rahman

Reputation: 637

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?

Upvotes: 13

Views: 17722

Answers (5)

Walter Roman
Walter Roman

Reputation: 4779

As of Angular 1.2.24*, there is an ng-blur directive.

// View
<input 
    type="text"
    placeholder="Hello World!"
    ng-model="foo.bar"
    ng-blur="onBlur($event)"
    >

// Controller
$scope.onBlur = function($event) {
    return $event;
}

* I don't know in which Angular version ng-blur was introduced.

Upvotes: 4

Thiago Mata
Thiago Mata

Reputation: 2959

The native ng-blur "Doesn't work at all in latest unstable. :(" http://docs.angularjs.org/api/ng.directive:ngBlur

Yo can fix this following the steps of this post "There is no direct support for blur event in AngularJs. But we can add support for blur event by creating directive." http://coding-issues.blogspot.in/2013/10/angularjs-blur-directive.html

Upvotes: 1

JQuery Guru
JQuery Guru

Reputation: 6963

You can use Angular UI @ http://angular-ui.github.io/ui-utils/ which provide Blurs, Focus, Double-Clicks event or Bind a callback to any event not natively supported by Angular Js

Below is one of the example of blur event:

<input ui-event="{ blur : 'blurCallback()' }">

<script>
$scope.blurCallback = function() {
alert('Goodbye');
};
</script>

Upvotes: 7

Jesus Rodriguez
Jesus Rodriguez

Reputation: 12018

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

Upvotes: 25

tamakisquare
tamakisquare

Reputation: 17067

Directives supporting focus and blur events will be included in the next AngularJS release (reference), which should be out soon (my guess is within the next month). If you can't wait, like JQueryGuru suggested, you can use the uiEvent directive from the AngularUI project.

Upvotes: 0

Related Questions