Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-blur the model's updated value is not avaiable in event

Tags:

angularjs

I am using the ng-model-options to prevent my text input's model from being updated until the focus is lost. That part all works. However, I need to handle the event after the text input loses focus and the model is updated. In that event I need access to the NEW model's updated value, not the old one.

I am trying to use the ng-blur event, however, inside my handler the value is the old value, not the new value entered. Am I doing something wrong or is there a better way to get the newly committed model value after the text input loses focus?

<input type="text"
ng-model-options="{ updateOn: 'blur', debounce:0 }"
ng-model="vm.myModel.amount"
ng-blur="vm.handleBlurEvent(vm.myModel.amount)" />


vm.handleBlurEvent = function(item)
{
            //alert(item.amount); //Old amount - not new amount entered
}
like image 335
Pacificoder Avatar asked Feb 28 '15 00:02

Pacificoder


People also ask

What is a blur event in Angular?

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.

What is the use of ng blur in AngularJS?

Definition and Usage 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.

What is Ngmodeloptions in angular?

The ng-model-options directive is used to control the binding of an HTML form element and a variable in the scope. You can specify that the binding should wait for a specific event to occur, or wait a specific number of milliseconds, and more, see the legal values listed in the parameter values below.


2 Answers

This is reworked from previous response by user1750537, delay the model update until control blur and then process the change once, no de-bounce required and the model value will be set before your change logic as expected.

<input type="text"
ng-model-options="{ updateOn: 'blur' }"
ng-model="vm.myModel.amount"
ng-change="vm.handleChangeEvent(vm.myModel.amount)" />

vm.handleChangeEvent = function(item)
{
   alert(item.amount); //new shows the NEW amount :-)
}
like image 135
Chris Schaller Avatar answered Sep 22 '22 08:09

Chris Schaller


Old question but I've found another way to read this value, I couldn't remove debounce with delay and what worked for me was using timeout:

  $timeout(function(){
    var amount = this.formName.amount.value;
  });

I think this = ngModelController in above code.

like image 32
Mahakala Avatar answered Sep 20 '22 08:09

Mahakala