Updating model after focus is lost on input control

All we need is an easy explanation of the problem, so here it is.

In this code:

<input class="form-control" ng-model="actionText" />

AngularJS will update the model actionText as the user types stuff in. If this model is being used elsewhere, such as in a controller, it gets updated as each character is typed. I can think of situations where that could actually be a bad thing. Maybe you only want the model value AFTER the user has moved focus from the input to something else, such as when you need to validate the input when it has completed. I could use Javascript’s blur function to setup a handler to determine when focus is lost but that seems to be against the way Angular is meant to be. Is there an AngularJS way of updating the model after the input has lost focus?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You can use the ngModelOptions directive for this. With ngModelOptions you can further refine how the ngModel directive works. To achieve what you asked for, you may use it like this:

<input class="form-control" ng-model="actionText" 
   ng-model-options="{ updateOn: 'blur'}"/>

You can find further information and a working example in the angular documentation: https://docs.angularjs.org/api/ng/directive/ngModelOptions

Method 2

I think the easiest way might be just use ng-blur to fire off something you want to do.

http://plnkr.co/edit/rhcliQRzUOBKQ3xKFrde?p=preview

app.controller('MainCtrl', function($scope) {

  $scope.myDataBlurred = $scope.myData;

  $scope.blurred = function() {
     $scope.myDataBlurred = $scope.myData;
  }
});

 <input ng-model='myData' ng-blur='blurred()' />

    <div>
      This will update as you type: {{myData}}
    </div>
    <div>
      This will update after you blur:  {{myDataBlurred}}
    </div>

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply