2

I cannot understand why my oldValue in $watchGroup is not updated.

I have simply code:

$scope.sort='date'
$scope.results = [];

$scope.click = function(){
  $scope.sort = 'name'
  $scope.order = !$scope.order
}

$scope.$watchGroup(['sort','order'],function(newVal,oldVal){
  $scope.results.push(newVal[0]+' '+oldVal[0]+'; ' +newVal[1] + ' ' + oldVal[1])
  console.log(newVal[0],oldVal[0],newVal[1],oldVal[1]);
});

I'm setting sort at the beggining to 'date' then with button click I change it to 'name'. Every click changes the value to 'name', but $watchGroup says the old value is still 'date'. The old order value is updated, but old sort value is not.

Can someone explain this strange behavior?

There is a plunkr: http://plnkr.co/edit/qpBp00tndmKqBarnfAgN?p=preview

akn
  • 3,712
  • 26
  • 43

1 Answers1

0

It makes sense, because the string literal name that you use, is the same one every time you assign it, so $scope.sort only changes the first time you click the button. (see here).

If you change your code to $scope.sort = new String('name'), you will see the behavior you expected, because that way you always create a new object, and your variable will point to a different place in the memory each time you click.

Community
  • 1
  • 1
Yaron Schwimmer
  • 5,327
  • 5
  • 36
  • 59