Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular ng-change in input textbox with old value

<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

like image 647
shrw Avatar asked Jan 03 '14 16:01

shrw


2 Answers

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}}
like image 200
Alborz Avatar answered Oct 08 '22 17:10

Alborz


Use ng-model-options

<input type="text" ng-model="a.b" ng-change="callScriptThenServer()" ng-model-options="{updateOn: 'blur'}"/>
like image 29
Niels Steenbeek Avatar answered Oct 08 '22 19:10

Niels Steenbeek