Angular ng-change in input textbox with old value

shrw picture shrw · Jan 3, 2014 · Viewed 80.8k times · Source
<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

Answer

Alborz picture Alborz · Jan 3, 2014

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}}