为什么我必须在这里调用 $scope.$digest() ? [英] Why do i have to call $scope.$digest() here?
问题描述
我创建了一个显示工具提示的指令:
I created a directive for showing tooltips:
app.directive('tooltip',function(){
return{
restrict: 'A',
link: function(scope,element,attr){
element.bind('mouseenter',function(e){
scope.setStyle(e);
});
}
}
});
对应的setStyle()
函数:
$scope.setStyle = function(e){
$scope.style = {
position: 'absolute',
// some other styles
};
$scope.$digest();
};
$scope.style
应用于此:
<span ng-style="style">I am a tooltip</span>
这是我视图的一部分,由拥有 $scope.style
which is part of my view, handled by the controller who owns $scope.style
为什么我必须调用 $digest()
才能将更改应用到 $scope.style
,它之前声明和初始化过?
Why do i have to call $digest()
in order to apply the changes to $scope.style
, which was declared and initialized earlier?
推荐答案
因为附加到 mouseenter
事件的回调超出了 angular 的范围;angular 不知道该函数何时运行/结束,因此永远不会运行摘要循环.
Because the callback attached to the mouseenter
event is outside of angular's scope; angular has no idea when that function runs/ends so the digest cycle is never ran.
调用 $digest
或 $apply
告诉 angular 更新绑定并触发任何手表.
Calling $digest
or $apply
tells angular to update bindings and fire any watches.
这篇关于为什么我必须在这里调用 $scope.$digest() ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!