ng-change get new value and original value

前端 未结 7 875
北荒
北荒 2020-11-28 22:20

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 th

相关标签:
7条回答
  • 2020-11-28 22:39

    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>
    
    0 讨论(0)
  • 2020-11-28 22:43

    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.

    0 讨论(0)
  • 2020-11-28 22:44

    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}}')">
    
    0 讨论(0)
  • 2020-11-28 22:44

    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

    0 讨论(0)
  • 2020-11-28 22:48

    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.

    0 讨论(0)
  • 2020-11-28 22:58

    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.

    0 讨论(0)
提交回复
热议问题