为什么我的 Angular 服务需要 `$rootScope.$apply()`? [英] Why do I need `$rootScope.$apply()` in my Angular Service?

查看:26
本文介绍了为什么我的 Angular 服务需要 `$rootScope.$apply()`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中有一个名为 Overlay 的弹出式模式服务.它只是在 $rootScope 上翻转一些布尔值,导致 2 个指令适当地显示/隐藏.这是显示新模态时调用的函数

I have a pop-up modal service in my application called Overlay. It simply flips some booleans on the $rootScope that cause 2 directives to show/hide appropriately. Here is the function that is called when showing a new modal

 overlay.NewGears = {
        show: function(msg){
            _displayBackground();

            scope.message = msg;
            scope.feedback = null;
            scope.url = '/partials/Common/gears.html';

            $rootScope.$apply(function(){
                $rootScope.modalVisible = true;
            });


        },
        hide: function(){
            _hideBackground();

            $rootScope.modalVisible = false;
        }
    };

如您所见,我显示了不透明的背景,然后我设置了一个名为 scope 的变量,该变量稍后通过 DI 传递到我的指令中.但是后来我注意到我的模态没有出现在它应该出现的时候,而是在 modalVisible 变量设置为 true 之后出现在 NEXT 摘要循环中.然后我不得不在作业周围添加 $apply() 以使其工作.但是,我认为这仅在我们处于Angular 世界"之外时才需要,那么为什么我需要在我的 Angular 服务中使用它?

As you can see I display the opaque background, then I set up a variable called scope which is later passed into my directive via DI. But then I noticed that my modal was not appearing when it should, and instead was appearing on the NEXT digest cycle after the modalVisible variable was set to true. I then had to add the $apply() around the assignment to get it to work. However, I thought this is only needed when we are outside the "Angular world", so why do I need this inside of my Angular Service?

推荐答案

$apply 需要告诉 angular 范围发生了变化.ngClick$http 等内置指令和服务在内部执行此操作.如果您对范围应用(原文如此!)更改并且不使用上述内置服务,那么您有责任自己调用 $apply.

$apply is necessary to tell angular that changes happened to the scope. Built-in directives and services like ngClick or $http do that internally. If you apply (sic!) changes to the scope and don't use the aforementioned built-in services, then you are responsible for calling $apply yourself.

因此,如果 show 未在 ngClick 处理程序中调用,例如,那么您需要自己调用 $apply.

So if show isn't called within an ngClickhandler, e.g., then you need to call $apply yourself.

这篇关于为什么我的 Angular 服务需要 `$rootScope.$apply()`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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