Skip to content

Commit bf69ca0

Browse files
author
Gonzalo Ruiz de Villa
committed
fix(rootScope): $watchCollection returns in oldCollection a copy of the former array data
related to angular#1751 When watching arrays, $watchCollection returned the new data both in the newCollection and the oldCollection arguments of the listener
1 parent 40c0220 commit bf69ca0

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

src/ng/rootScope.js

+5-1
Original file line numberDiff line numberDiff line change
@@ -362,6 +362,7 @@ function $RootScopeProvider(){
362362
$watchCollection: function(obj, listener) {
363363
var self = this;
364364
var oldValue;
365+
var oldArray;
365366
var newValue;
366367
var changeDetected = 0;
367368
var objGetter = $parse(obj);
@@ -371,6 +372,7 @@ function $RootScopeProvider(){
371372

372373
function $watchCollectionWatch() {
373374
newValue = objGetter(self);
375+
oldArray = null;
374376
var newLength, key;
375377

376378
if (!isObject(newValue)) {
@@ -386,6 +388,8 @@ function $RootScopeProvider(){
386388
changeDetected++;
387389
}
388390

391+
oldArray = oldValue.slice(0);
392+
389393
newLength = newValue.length;
390394

391395
if (oldLength !== newLength) {
@@ -439,7 +443,7 @@ function $RootScopeProvider(){
439443
}
440444

441445
function $watchCollectionAction() {
442-
listener(newValue, oldValue, self);
446+
listener(newValue, oldArray || oldValue, self);
443447
}
444448

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

test/ng/rootScopeSpec.js

+22
Original file line numberDiff line numberDiff line change
@@ -510,6 +510,28 @@ describe('Scope', function() {
510510
$rootScope.$digest();
511511
expect(arrayLikelog).toEqual(['x', 'y']);
512512
});
513+
514+
it('should return a new array with old values', function(){
515+
var watchArgs;
516+
$rootScope.$watchCollection('obj', function (newValues, oldValues) {
517+
watchArgs = {
518+
newValues: newValues,
519+
oldValues: oldValues
520+
};
521+
});
522+
523+
$rootScope.obj = ['a'];
524+
$rootScope.$digest();
525+
526+
expect(watchArgs.newValues).toEqual($rootScope.obj);
527+
expect(watchArgs.oldValues).toEqual([]);
528+
529+
$rootScope.obj.push('b');
530+
$rootScope.$digest();
531+
532+
expect(watchArgs.newValues).toEqual(['a', 'b']);
533+
expect(watchArgs.oldValues).toEqual(['a']);
534+
})
513535
});
514536

515537

0 commit comments

Comments
 (0)