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?
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.
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.
blur() method removes keyboard focus from the current element.
If you don't want to use angular-ui's ui-event
, you can also create a small directive until the next version of Angular
is 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With