$在setTimeout中应用 [英] $apply in setTimeout
问题描述
我知道$apply
用于连接Javascript上下文和AngularJS上下文.
I konw that $apply
used to connect the Javascript context and the AngularJS context.
下面是一个简单的示例:
A simple example is below:
模板:
<div>{{someVal}}</div>
控制器中的javascript:
javascript in controller:
setTimeout(function() {
scope.$apply(function(){scope.someVal = 123});
}, 1000);
在上述情况下,我们需要使用$apply
.
We need use $apply
in above situation.
第一个问题:
如果我将上面的javascript修改为:
If I modify javascript above to:
setTimeout(function() {
scope.someVal = 123;
}, 1000);
scope.$watch('someVal', function(val) {
console.info(someVal);
});
没有关于someVal的控制台修改为123 ...为什么?我们不能看在超时回调中修改的表达式吗?
No console about someVal modified to 123... Why? Can't we watch expression modified in timeout callback?
第二个问题:
如果我们使用ngSwitch指令,如下所示:
If we use ngSwitch directive like below:
<div ng-switch on="sub">
<div ng-switch-when="a">
//state a
</div>
<div ng-switch-when="b">
//state b
</div>
</div>
当我在控制器中修改sub
时:
When I modify the sub
in controller:
scope.sub = 'a';
setTimeout(function() {
scope.sub = 'b';
}, 1000);
无需使用$apply
!!!!为什么?
No need to use $apply
!!!! Why?
我发现ngSwitch指令使用$watch
监视on
属性值.为什么ngSwitch可以观看在超时回调中修改的范围属性?????
I found that ngSwitch directive use $watch
to monitor on
attribute value. Why ngSwitch can watch scope attribute modified in timeout callback?????
请告诉我上述两个问题的原因.
Pls tell me the reason about the 2 qustions above.
推荐答案
来自 AngularJs 文档
$ apply()用于从角度框架外部以角度执行表达式. (例如,来自浏览器的DOM事件,setTimeout,XHR或第三方库).因为我们正在调用角度框架,所以我们需要执行适当的范围范围的异常处理生命周期,并执行监视.
$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 exception handling, executing watches.
window.setTimeout 是JavaScript函数,所以无论如何您使用setTimeout
,您必须使用$ apply()来更新模型.
window.setTimeout is a JavaScript function, so whatever you use setTimeout
you must use $apply() to update the model.
您的第二个示例如果没有$apply()
,将无法正常工作,我制作了
Your second example wouldn't work without $apply()
, I've made a demo to clarify the $watch
and $apply
issue. Please check it.
这篇关于$在setTimeout中应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!