[angularjs] ng-change get new value and original value

I'm using ng-options to select values from a pulldown. I'd like to be able to compare the old value to the new value. ng-change works well for grabbing the new value of the pull down, but how can I get both the new value and the original value?

<select ng-change="updateValue(user)" ng-model="user.id" ng-options="user.id as user.name for user in users"></select> 

For instance, let's say I wanted the controller to log, "Your former user.name was BILL, your current user name is PHILLIPE."

This question is related to angularjs ng-options

The answer is


With an angular {{expression}} you can add the old user or user.id value to the ng-change attribute as a literal string:

<select ng-change="updateValue(user, '{{user.id}}')" 
        ng-model="user.id" ng-options="user.id as user.name for user in users">
</select>

On ngChange, the 1st argument to updateValue will be the new user value, the 2nd argument will be the literal that was formed when the select-tag was last updated by angular, with the old user.id value.


You can use something like ng-change=someMethod({{user.id}}). By keeping your value in side {{expression}} it will evaluate expression in-line and gives you current value(value before ng-change method is called).

<select ng-model="selectedValue" ng-change="change(selectedValue, '{{selectedValue}}')">

You can always do:

... ng-model="file.PLIK_STATUS" ng-change="file.PLIK_STATUS = setFileStatus(file.PLIK_ID,file.PLIK_STATUS,'{{file.PLIK_STATUS}}')" ...

and in controller:

$scope.setFileStatus = function (plik_id, new_status, old_status) {
    var answer = confirm('Czy na pewno zmienic status dla pliku ?');
    if (answer) {
        podasysService.setFileStatus(plik_id, new_status).then(function (result) {
            return new_status;
        });
    }else{
        return old_status;
    }
};

Also you can use

<select ng-change="updateValue(user, oldValue)"     
       ng-init="oldValue=0"
       ng-focus="oldValue=user.id"
       ng-model="user.id" ng-options="user.id as user.name for user in users">
</select>

You can use a scope watch:

$scope.$watch('user', function(newValue, oldValue) {
  // access new and old value here
  console.log("Your former user.name was "+oldValue.name+", you're current user name is "+newValue.name+".");
});

https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watch


Just keep a currentValue variable in your controller that you update on every change. You can then compare that to the new value every time before you update it.'

The idea of using a watch is good as well, but I think a simple variable is the simplest and most logical solution.


You could use a watch instead, because that has the old and new value, but then you're adding to the digest cycle.

I'd just keep a second variable in the controller and set that.