ng-change get new value and original value

Bailey Smith picture Bailey Smith · Oct 29, 2014 · Viewed 137.6k times · Source

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."

Answer

db-inf picture db-inf · Jan 20, 2015

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.