为什么我必须在这里调用$ scope$ digest()?

【字号: 日期:2024-04-10浏览:41作者:雯心
(adsbygoogle = window.adsbygoogle || []).push({}); 如何解决为什么我必须在这里调用$ scope$ digest()??

因为附加到mouseenter事件的回调超出了angular的范围;angular不知道该函数何时运行/结束,因此摘要循环永远不会运行。

调用$digest或$apply告诉angular更新绑定并触发任何手表。

解决方法

我创建了一个用于显示工具提示的指令:

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

为什么必须调用$digest()才能将更改应用到$scope.style,该更改是早先声明和初始化的?

相关文章: