简体   繁体   中英

Click off input field event in Angular JS

Suppose you have an input field in an Angular JS app

 <input id="title" type="text" name="title" placeholder="enter a title" ng-model="item.title" />

I would like to display some feedback to the user about the validity of the input data AFTER the user has completed interacting with the input but I cannot think of a directive to watch the "click off" event. That is, when a user types into the form, then either tabs next or clicks anywhere else.

How do I capture the "click off and element" event.

Please note, this is in contrast to an "off-click" event, where the event refers to when a user clicks anywhere BUT a given element.

You need to use ng-blur directive.

ng-blur:

Specify custom behavior on blur event.

A blur event fires when an element has lost focus.

Note: the print you see in the ng-blur is nothing but console.log using this for convenience, refer my fiddle!

JS:

<div ng-controller='MyController' ng-app="myApp">
  <input id="title" type="text" name="title" placeholder="enter a title" ng-model="item.title" ng-blur="print('lost focus')" />
</div>

References:

  1. ng-blur

As mentioned in Naren's answer, ngBlur is the directive you are looking for.

However, since you're trying to implement validation, you should know that angular has built-in validation functionality that will handle the events for you and using them is a better practice than reinventing the validation 'wheel'.

Use validation directives like ngRequired, ngMinlength, ngMaxlength and ngPattern for simple validation needs.

https://docs.angularjs.org/guide/forms

Use Angular UI's uiValidate directive for custom validation including validation through asynchronous http requests.

https://github.com/angular-ui/ui-validate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM