angularjsng-options

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


Solution

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