Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

Commit 1d7a95d

Browse files
mernenmhevery
authored andcommitted
feat(scope): only evaluate constant $watch expressions once
1 parent 1ed6385 commit 1d7a95d

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

src/ng/rootScope.js

+8
Original file line numberDiff line numberDiff line change
@@ -300,6 +300,14 @@ function $RootScopeProvider(){
300300
watcher.fn = function(newVal, oldVal, scope) {listenFn(scope);};
301301
}
302302

303+
if (typeof watchExp == 'string' && get.constant) {
304+
var originalFn = watcher.fn;
305+
watcher.fn = function(newVal, oldVal, scope) {
306+
originalFn.call(this, newVal, oldVal, scope);
307+
arrayRemove(array, watcher);
308+
};
309+
}
310+
303311
if (!array) {
304312
array = scope.$$watchers = [];
305313
}

test/ng/rootScopeSpec.js

+13-1
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,14 @@ describe('Scope', function() {
9999
expect(spy).wasCalled();
100100
}));
101101

102+
it('should not keep constant expressions on watch queue', inject(function($rootScope) {
103+
$rootScope.$watch('1 + 1', function() {});
104+
expect($rootScope.$$watchers.length).toEqual(1);
105+
$rootScope.$digest();
106+
107+
expect($rootScope.$$watchers.length).toEqual(0);
108+
}));
109+
102110

103111
it('should delegate exceptions', function() {
104112
module(function($exceptionHandlerProvider) {
@@ -119,10 +127,14 @@ describe('Scope', function() {
119127
var log = '';
120128
$rootScope.$watch('a', function() { log += 'a'; });
121129
$rootScope.$watch('b', function() { log += 'b'; });
130+
// constant expressions have slightly different handling,
131+
// let's ensure they are kept in the same list as others
132+
$rootScope.$watch('1', function() { log += '1'; });
122133
$rootScope.$watch('c', function() { log += 'c'; });
134+
$rootScope.$watch('2', function() { log += '2'; });
123135
$rootScope.a = $rootScope.b = $rootScope.c = 1;
124136
$rootScope.$digest();
125-
expect(log).toEqual('abc');
137+
expect(log).toEqual('ab1c2');
126138
}));
127139

128140

0 commit comments

Comments
 (0)