Michael Michael - 3 months ago 15
AngularJS Question

How to get new selected and old values after user selected option from dropdown list box?

I have angularjs dropdown list box:

<select class="form-control"
ng-model="editor.frequency"
ng-options="item as item.Name for item in editor.frequencies"
ng-change="editor.editFrequencyManual = false;">
</select>


After user click on option in dropdown list box I need to get clicked(selected) value and the old value(before selection).

Any idea how can I get this two values?Is there event function that I sholud use?

gyc gyc
Answer

You could watch the changes on your model:

$scope.$watch('editor', function(newValue, oldValue){
    //
});

Or you could modify ng-change so that it passes old and new values as parameters:

    <select class="form-control"
            ng-model="editor.frequency"
            ng-options="item as item.Name for item in editor.frequencies"
            ng-change="changed(editor.frequency, {{editor.frequency}}); editor.editFrequencyManual = false;">
   </select>

Of course, you should move editor.editFrequencyManual = false; into the change function.

function myController($scope) {
  $scope.myModel = {};
  $scope.doThis = function(newValue, oldValue) {
    console.log("New value: " + newValue);
    console.log("Old value: " + oldValue);
  }
}

angular.module('myApp', []);
angular
  .module('myApp')
  .controller('myController', myController);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="myController">
      <select ng-model="myModel" ng-change="doThis(myModel, '{{myModel}}');">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
      </select>
    </div>
</div>