Search code examples
javascriptangularjsmouseclick-event

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.


Solution

  • 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!

    JSFiddle Demo

    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