为什么我必须在这里调用 $scope.$digest() ? [英] Why do i have to call $scope.$digest() here?

查看:24
本文介绍了为什么我必须在这里调用 $scope.$digest() ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆