Angular ng-change in input textbox with old value

81.9k Views Asked by At
<input type="text" id="exampleab"
ng-model="a.b"
ui-event="{ blur : 'callScriptThenServer()' }" >

For some reasons the ng-change on textbox is not working so i am using it; Using Angular-ui's ui-events.

PROBLEM

I want to call the function only if the value is changed and also want the old value in callback.(since I want to send the oldValue to the server).

I don't want to go via pure directives route because there are so many occurrences of these

NG-CHANGE : on each character changed i get a callback . I don't want that. I need to call the server script .. with the old value in the text box and the new value after blur

4

There are 4 best solutions below

1
On

You can use AngularJS Watch

$scope.$watch(function(){
    return $scope.a.b;
}, function(newvalue, oldvalue){
    //Here You have both newvalue & oldvalue
    alert("newvalue: " + newvalue);
    alert("oldvalue: " + oldvalue);
},true);

Plunkr DEMO

5
On

You can watch your variable to have the newValue and oldValue at the same time.

<input type="text" id="exampleab" ng-model="a.b"  >

In your controler:

app.controller('ctrl', function ($scope) {
    $scope.$watch('a.b', function (newValue, oldValue) {
        console.log('oldValue=' + oldValue);
        console.log('newValue=' + newValue);
        //do something
    });
});

JSFiddle

EDIT You mentioned a new requirement in your edit so i edit my answer. You shouldn't use ng-change. you should get the oldValue when the control being focused and save it in a variable and then get the new value on blur event. I set up a new fiddle.

In your controller :

    app.controller('ctrl', function ($scope) {
        $scope.showValues = function () {
            alert('oldValue = ' + $scope.oldValue);
            alert('newValue = ' + $scope.a.b);
        }
    });

I your view

<input type="text" id="exampleab" ng-model="a.b" ng-init="oldValue = ''" ng-focus="oldValue = a.b" ng-blur="showValues()" />{{a.b}}
0
On

Use ng-model-options

<input type="text" ng-model="a.b" ng-change="callScriptThenServer()" ng-model-options="{updateOn: 'blur'}"/>
0
On

Use Angular ngModelOptions with getterSetter:true; and then use method call inside the "set" part of the function.

See the last example on this page: https://docs.angularjs.org/api/ng/directive/ngModelOptions