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

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

问题描述

我在我的应用程序弹出模式服务名为覆盖。它只是翻转的 $ 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;
        }
    };

正如你可以看到我显示不透明的背景,那么我成立了一个名为范围变量这就是后来传入通过DI我的指令。但后来我发现我的语气不是当它应该是出现在NEXT消化周期 modalVisible 变量设置为true后出现的,而是。然后我不得不添加 $适用()分配各地得到它的工作。不过,我认为这时候我们是世界角外,才需要,那么为什么我需要这个我折角服务里面?

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?

推荐答案

$适用是必要告诉角度的更改发生的范围。内置指令和服务,如 ngClick $ HTTP 做内部。如果应用(原文如此!)变化的范围和不使用上述内置服务,那么你是负责调用 $适用自己。

$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.

所以,如果显示 ngClick 处理程序内不叫,例如,那么你就需要调用 $适用自己。

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

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

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