$在setTimeout中应用 [英] $apply in setTimeout
问题描述
我知道 $apply
用于连接 Javascript 上下文和 AngularJS 上下文.
一个简单的例子如下:
模板:
{{someVal}}
控制器中的javascript:
setTimeout(function() {scope.$apply(function(){scope.someVal = 123});}, 1000);
我们需要在上述情况下使用 $apply
.
第一个问题:
如果我将上面的 javascript 修改为:
setTimeout(function() {范围.someVal = 123;}, 1000);scope.$watch('someVal', function(val) {控制台信息(someVal);});
关于 someVal 的控制台没有修改为 123...为什么?超时回调中修改的表达式不能看吗?
第二个问题:
如果我们使用如下的 ngSwitch 指令:
<div ng-switch-when="a">//状态a<div ng-switch-when="b">//状态b
当我修改控制器中的 sub
时:
scope.sub = 'a';设置超时(功能(){scope.sub = 'b';}, 1000);
无需使用$apply
!!!为什么?
我发现 ngSwitch 指令使用 $watch
来监控 on
属性值.为什么ngSwitch可以监听超时回调中修改的scope属性??????
请告诉我上述 2 个问题的原因.
来自 AngularJs 文档
<块引用>$apply() 用于从 angular 框架外部执行 angular 表达式.(例如来自浏览器 DOM 事件、setTimeout、XHR 或第三方库).因为我们正在调用 angular 框架,所以我们需要执行异常处理、执行监视的适当范围生命周期.
window.setTimeout 是一个 JavaScript 函数,所以不管您使用 setTimeout
您必须使用 $apply() 来更新模型.
你的第二个例子没有 $apply()
就行不通,我做了一个 demo 阐明 $watch
和 $apply代码> 问题.请检查一下.
I konw that $apply
used to connect the Javascript context and the AngularJS context.
A simple example is below:
template:
<div>{{someVal}}</div>
javascript in controller:
setTimeout(function() {
scope.$apply(function(){scope.someVal = 123});
}, 1000);
We need use $apply
in above situation.
First Qustion:
If I modify javascript above to:
setTimeout(function() {
scope.someVal = 123;
}, 1000);
scope.$watch('someVal', function(val) {
console.info(someVal);
});
No console about someVal modified to 123... Why? Can't we watch expression modified in timeout callback?
Second Question:
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>
When I modify the sub
in controller:
scope.sub = 'a';
setTimeout(function() {
scope.sub = 'b';
}, 1000);
No need to use $apply
!!!! Why?
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.
From AngularJs documentation
$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 is a JavaScript function, so whatever you use setTimeout
you must use $apply() to update the model.
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屋!