angularjs $watch old value and new value are the same

后端 未结 4 1036
忘了有多久
忘了有多久 2020-12-30 20:29

My intention is to watch a model within scope, and find difference between old value and new value.

However, I found old value and new value are all the same from th

相关标签:
4条回答
  • 2020-12-30 21:03

    This is a bug.

    https://github.com/angular/angular.js/issues/2621

    and it seems not being fixed.

    0 讨论(0)
  • 2020-12-30 21:06

    You can use $watch instead, that seems to work. If you want to watch all the properties on the object as well (as you are doing), you need to add true as the third parameter to the watch. This sets up a deep watch.

    Here is a working plunker.

    JS:

    app = angular.module('myApp',[]);
    
    app.controller('MyCtrl', function($scope, $timeout){
      $scope.markers = {};
      $scope.$watch('markers', function(newValue, oldValue){
        console.log('being watched oldValue:', oldValue, 'newValue:', newValue);
      }, true);
      $timeout( function() {
        $scope.markers.foo = 1;
      }, 500);
      $timeout( function() {
        $scope.markers.bar = 2;
      }, 500);
    });
    
    0 讨论(0)
  • 2020-12-30 21:13

    The values are passed as parameters

    $scope.$watch('foo', function (newValue, oldValue) {
      // ...
    }
    
    0 讨论(0)
  • 2020-12-30 21:17

    I found that it's very useful to check if the new and old value are equal (in values) and skip the process if that's the case to avoid unexpected behavior. You can use angular.equals to achieve that. Here's an example:

    JS:

    $scope.$watch('myObject', function(newValue, oldValue){
        if(angular.equals(newValue, oldValue)){
            return; // simply skip that
        }
    });
    
    0 讨论(0)
提交回复
热议问题