Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angularjs 为什么我必须在这里调用$scope.$digest()?_Angularjs_Data Binding_Angularjs Directive - Fatal编程技术网

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

Angularjs 为什么我必须在这里调用$scope.$digest()?,angularjs,data-binding,angularjs-directive,Angularjs,Data Binding,Angularjs Directive,我创建了一个用于显示工具提示的指令: app.directive('tooltip',function(){ return{ restrict: 'A', link: function(scope,element,attr){ element.bind('mouseenter',function(e){ scope.setStyle(e); }); }

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

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

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

调用
$digest
$apply
会通知angular更新绑定并触发任何监视。

元素。bind()
意味着侦听特定的浏览器事件,并在元素上调度此事件时执行回调。在这一连串的事件中,没有一个是包括在内的——它不知道事件发生了。因此,您必须明确地告诉它有关该事件的信息。但是,在大多数情况下,您应该使用
$scope.$apply()
而不是
$scope.$digest()
,尤其是在您不确定的情况下

以下是更适合您的情况的代码:

app.directive('tooltip',function(){
    return{
        restrict: 'A',
        link: function(scope,element,attr){
            element.bind('mouseenter',function(e){
                scope.setStyle(e);
                scope.$apply();
            });
        }
    }
});
setStyle()

$scope.apply()有两个实现,一个没有参数,另一个将函数作为参数,对其求值并触发摘要()。使用后一种方法具有优势,因为它将函数封装在try/catch子句中,该子句由$exceptionHandler服务处理

尽管如此,您也可以这样做:

$scope.$apply(scope.setStyle(e));

这将包装要应用的函数调用并自动触发摘要。

链接到哪些元素“$scope.style”?如果你能为这个做一把小提琴,那将是非常有帮助的。@Web我补充了我的帖子,稍后将提供一把小提琴。现在工作结束:)ng的源代码单击:非常感谢。用这种方法解决这个问题有什么缺点吗?我应该考虑另一种架构吗?不,这是你在角度范围之外必须做的事情。更好的方法是在指令中包含
$digest/$apply
调用:
scope.$apply(function(){scope.setStyle(e);})$scope.$apply()调用$rootScope.$digest(),因此您可能需要调用$scope.$apply()或$rootScope.$digest()。调用$scope。$digest()意味着您将摘要限制在本地范围内。从技术上讲,这并不是在$apply调用中包装您的
setStyle
调用
setStyle
返回并将其返回值传递给$apply。它在大多数情况下仍然有效,但可能有点误导。
$scope.$apply(scope.setStyle(e));