angular.js icon indicating copy to clipboard operation
angular.js copied to clipboard

$watchCollection newValue always == oldValue

Open mattlanders opened this issue 13 years ago • 58 comments

I trying to use the $watchCollection to watch an array, and I noticed that the newvalue is always equal to the oldvalue. After looking at the code, it looks like the values are copied to oldValue prior to firing the listener. It should be an easy fix.

mattlanders avatar May 09 '13 17:05 mattlanders

I noticed this too when trying to iterate over the oldCollection to remove Google Maps markers.

Soviut avatar May 25 '13 22:05 Soviut

Reduction:

http://jsfiddle.net/Y8yEZ/6/

appsforartists avatar May 31 '13 07:05 appsforartists

I think you mean "reproduction". I legitimately thought maybe you were talking about a "reduce" function at first ;)

Soviut avatar May 31 '13 07:05 Soviut

@Soviut http://www.webkit.org/quality/reduction.html

appsforartists avatar May 31 '13 07:05 appsforartists

Ah I see. I've always just called them test cases, examples or even proofs. I still stand by the fact that the language is ambiguous given that "reduce" is a common enough term general programming.

Thanks for the test case/example/proof though! ;)

Soviut avatar May 31 '13 08:05 Soviut

$watchCollection seems to be exceptionally flaky. Not only is there this unbelievably glaring issue (really, I'm not sure how a bug this big makes it to release at a place like Google), but in my limited testing, it seems to be behaving more like a deep watch than a shallow one. It's not my codebase, so I don't yet know if there's something particularly funky in the app, but I'm getting watchCollection calls just by changing the details of objects nested within the array I'm watching.

appsforartists avatar May 31 '13 08:05 appsforartists

There isn't much documentation on $watchCollection so the intent is a bit ambiguous. On first thought, I'd say that bubbling child events through the parent collection makes sense. That said, how do you only get it to watch the collection itself?

Soviut avatar May 31 '13 08:05 Soviut

$watchCollection: Shallow watches the properties of an object and fires whenever any of the properties change (for arrays this implies watching the array items, for object maps this implies watching the properties).

-- docs

If you want to deep watch, you can $scope.$watch(..., true).

For instance:

cart = []

$scope.$watch(cart, listenerA, false);     // standard watch
$scope.$watch(cart, listenerB, true);      // deep watch
$scope.$watchCollection(cart, listenerC);  // shallow watch

cart = [{'item': 'blackberries', 'quantity': 3}, {'item': 'pears',

'quantity': 1}]; // The value of cart is now different and all three listeners fire.

cart.push({'item': 'apples', 'quantity': 5});
// The value of cart is the same, but it contains a new value.

listenerB and listenerC fire.

cart[0].quantity++;
// The value of cart is the same and it has the same contents.  A

property on one of the items in the cart has changed. Only listenerB fires.

On Fri, May 31, 2013 at 1:12 AM, Soviut [email protected] wrote: There isn't much documentation on $watchCollection so the intent is a bit ambiguous. On first thought, I'd say that bubbling child events through the parent collection makes sense. That said, how do you only get it to watch the collection itself?

— Reply to this email directly or view it on GitHub.

appsforartists avatar May 31 '13 08:05 appsforartists

Here's a new test for this:

https://github.com/Versal/angular.js/commit/2c83c089ea9297b96b697a64e70cb46d0f0299b0?w=0

appsforartists avatar May 31 '13 22:05 appsforartists

@mattlanders I followed your advice and moved all the side-effects from watchCollectionWatch into watchCollectionAction, leaving only the change detecting logic in watchCollectionWatch. Unfortunately, that doesn't seem to work. (The watchCollection tests are all failing now.)

I'd have to spend some more time reading and debugging this before I'd be able to submit a solid pull request.

appsforartists avatar Jun 01 '13 00:06 appsforartists

Alright. I'm getting close. Here's the work so far.

All the watchCollection tests are passing. Here are the failures:

FAILED ngRepeat stability should throw error on adding existing duplicates and recover 
FAILED ngRepeat stability should throw error on new duplicates and recover 

And here is the error causing those failures:

[NgErr27] 10 $digest() iterations reached. Aborting!  Watchers fired in the last 5 iterations: []

The fixed version of watchCollection seems to be triggering more digests than the old version. I had to add this line to keep duplicate lines from showing up in the watchCollection tests. I imagine that whatever was causing watchCollectionAction to be called multiple times in digest is the same thing causing these failures.

appsforartists avatar Jun 05 '13 22:06 appsforartists

Also, I added a note to the docs about newCollection and oldCollection being of different types. It would be a better choice if newCollection and oldCollection were always the same type (in this case, a POJO or an Array), but that has the potential to be a breaking change.

appsforartists avatar Jun 05 '13 22:06 appsforartists

Don't know if someone will need this, but it seems that this $watchCollection bug still present in future 1.1.6 release. As a way to temporary bypass this bug one could simply use the 'normal' $watch function like this:

     $scope.model.cart = [1,2,3];
     function getArray(){
       return $scope.model.cart;
     }
     function doSomething(newValues, oldValues){
      //...
     }
     $scope.$watch(getArray, doSomething, true);  //deep watch

ivoreis avatar Jun 24 '13 19:06 ivoreis

It's not doing a deep compare. It checks references for each high-level key (object) or index (array). The problem is that it makes a shallow copy from newValue to oldValue, so when the watch function returns, newValue = oldValue, kind of. I made a quick fix,adding a third state called olderValue and returning newValue and olderValue from the listener. It works for me but I haven't run the official tests.

      $watchCollection: function(obj, listener) {
        var self = this;
        var olderValue;
        var oldValue;
        var newValue;
        var changeDetected = 0;
        var objGetter = $parse(obj);
        var internalArray = [];
        var internalObject = {};
        var oldLength = 0;

        function $watchCollectionWatch() {
          if (!isObject(oldValue)) {
              olderValue = oldValue;
          } else if (isArrayLike(oldValue)) {
              olderValue = [];
              for (var i = 0; i < oldLength; i++) {
                  olderValue[i] = oldValue[i];
              }
          } else {
              olderValue = {};
              for (key in oldValue) {
                  if (oldValue.hasOwnProperty(key)) {
                      olderValue[key] = oldValue[key];
                  }
              }
          }

          newValue = objGetter(self);
          var newLength, key;

          if (!isObject(newValue)) {
            if (oldValue !== newValue) {
              oldValue = newValue;
              changeDetected++;
            }
          } else if (isArrayLike(newValue)) {
            if (oldValue !== internalArray) {
              // we are transitioning from something which was not an array into array.
              oldValue = internalArray;
              oldLength = oldValue.length = 0;
              changeDetected++;
            }

            newLength = newValue.length;

            if (oldLength !== newLength) {
              // if lengths do not match we need to trigger change notification
              changeDetected++;
              oldValue.length = oldLength = newLength;
            }
            // copy the items to oldValue and look for changes.
            for (var i = 0; i < newLength; i++) {
              if (oldValue[i] !== newValue[i]) {
                changeDetected++;
                oldValue[i] = newValue[i];
              }
            }
          } else {
            if (oldValue !== internalObject) {
              // we are transitioning from something which was not an object into object.
              oldValue = internalObject = {};
              oldLength = 0;
              changeDetected++;
            }
            // copy the items to oldValue and look for changes.
            newLength = 0;
            for (key in newValue) {
              if (newValue.hasOwnProperty(key)) {
                newLength++;
                if (oldValue.hasOwnProperty(key)) {
                  if (oldValue[key] !== newValue[key]) {
                    changeDetected++;
                    oldValue[key] = newValue[key];
                  }
                } else {
                  oldLength++;
                  oldValue[key] = newValue[key];
                  changeDetected++;
                }
              }
            }
            if (oldLength > newLength) {
              // we used to have more keys, need to find them and destroy them.
              changeDetected++;
              for(key in oldValue) {
                if (oldValue.hasOwnProperty(key) && !newValue.hasOwnProperty(key)) {
                  oldLength--;
                  delete oldValue[key];
                }
              }
            }
          }
          return changeDetected;
        }

        function $watchCollectionAction() {
          listener(newValue, olderValue, self);
        }

        return this.$watch($watchCollectionWatch, $watchCollectionAction);
      },

johnsoftek avatar Aug 22 '13 15:08 johnsoftek

Hi Any news on this issue. are there any plans to fix it ?

ryan65 avatar Nov 24 '13 12:11 ryan65

Unfortunately this issue is still present in Angular 1.2.3. Would love to see a fix. Heads up :)

m0x72 avatar Dec 16 '13 18:12 m0x72

+1 this is a pretty serious blocker for us

xiehan avatar Dec 20 '13 16:12 xiehan

1.2.5, still a bug. http://plnkr.co/edit/rfMCF4x6CmVVT957DPSS?p=preview

allenhwkim avatar Dec 24 '13 00:12 allenhwkim

:+1:

alfonsodev avatar Dec 26 '13 18:12 alfonsodev

+1

scchadwi avatar Dec 30 '13 17:12 scchadwi