$apply=function(expr) {
try {
beginPhase('$apply');
try {
return this.$eval(expr);
} finally {
clearPhase();
}
} catch (e) {
$exceptionHandler(e);
} finally {
try {
$rootScope.$digest();
} catch (e) {
$exceptionHandler(e);
throw e;
}
}
}
版本:1.5.8 源码位置:17778行左右
- 使用$apply()方法可以手动触发angular的脏检查机制以监测自定数据的变化并使视图即时修改
angular的脏检查机制是由$digest主导的,但使用$apply方法更安全
原因:
如上代码,$apply方法传入表达式expr时,会首先调用$eval()方法来检查传入的表达式是否合法
如果不合法,则通过$exceptionHandler()处理
合法:再触发$digest()循环
优点:更加安全
改进:给apply传入一个函数做为参数以指定检查范围,不传入的话会默认检查全局的数据
官方描述:
@description
*$apply()
is used to execute an expression in angular from outside of the angular
* framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
* Because we are calling into the angular framework we need to perform proper scope life
* cycle of {@link ng.$exceptionHandler exception handling},