@@ -165,22 +165,40 @@ function createScope(parent, providers, instanceCache) {
165
165
}
166
166
} ,
167
167
168
- $watch : function ( watchExp , listener , exceptionHandler ) {
168
+
169
+ /**
170
+ * Registers `listener` as a watcher of the `watchExp` and executes it (optional, see `initRun`
171
+ * flag). Afterwards `listener` is executed every time the result of `watchExp` changes.
172
+ *
173
+ * The `listener` function will be called with two parameters `newValue` and `oldValue`.
174
+ *
175
+ * @param {Function|string } watchExp Expression that yields results. Can be an angular string
176
+ * expression or a function.
177
+ * @param {Function|string } listener Function (or angular string expression) that gets called
178
+ * every time the value of the `watchExp` changes.
179
+ * @param {Function } exceptionHanlder Handler that gets called when listeners throws an
180
+ * exception.
181
+ * @param {boolean } [initRun=true] Flag that prevents the first execution of the listener upon
182
+ * registration.
183
+ */
184
+ $watch : function ( watchExp , listener , exceptionHandler , initRun ) {
169
185
var watch = expressionCompile ( watchExp ) ,
170
- last = { } ;
186
+ last = watch . call ( instance ) ;
171
187
listener = expressionCompile ( listener ) ;
172
- function watcher ( ) {
188
+ function watcher ( firstRun ) {
173
189
var value = watch . call ( instance ) ,
190
+ // we have to save the value because listener can call ourselves => inf loop
174
191
lastValue = last ;
175
- if ( last !== value ) {
192
+ if ( firstRun || lastValue !== value ) {
176
193
last = value ;
177
194
instance . $tryEval ( function ( ) {
178
195
return listener . call ( instance , value , lastValue ) ;
179
196
} , exceptionHandler ) ;
180
197
}
181
198
}
182
199
instance . $onEval ( PRIORITY_WATCH , watcher ) ;
183
- watcher ( ) ;
200
+ if ( isUndefined ( initRun ) ) initRun = true ;
201
+ if ( initRun ) watcher ( true ) ;
184
202
} ,
185
203
186
204
$onEval : function ( priority , expr , exceptionHandler ) {
0 commit comments