错误:$rootScope:inprog -- 在 angular 中“不"执行 $apply 的正确方法是什么? [英] Error: $rootScope:inprog -- What is the correct way to 'not' execute $apply in angular?

查看:26
本文介绍了错误:$rootScope:inprog -- 在 angular 中“不"执行 $apply 的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

AngularJS Wiki - Anti-Patterns 声明如下:

不要做 if (!$scope.$$phase) $scope.$apply(),这意味着你的 $scope.$apply()在调用堆栈中不够高.

Don't do if (!$scope.$$phase) $scope.$apply(), it means your $scope.$apply() isn't high enough in the call stack.

我有点理解这一点.有一个内置的逻辑来确定何时需要执行什么.当外部开发人员在不同过程的运行时执行中没有直接的指导时,确定应该在何处运行什么,它会抵消框架.

And I kind of understand this. There is a built in logic that determines when what needs to be executed. And when an external developer, without direct insigt in the runtime executions of different procedures, determines what should run where, it counteracts the framework.

但我目前正在上传一个大文件,上传进度通过进度条显示.我使用的库 (resumableJS) 反过来有一个名为 fileProgress 的事件,它在上传进行时调用.如果我在那次活动中什么都不做,栏就不会更新.如果我把 $scope.$apply() 放在那里,栏会相应地更新,但我得到摘要和/或应用已经在进行中错误.最后,在 $$phase 检查的帮助下,我获得了两全其美的结果,一个没有任何错误的更新进度条.

But I am currently uploading a large file where the upload progress is displayed through a progress bar. The library I use (resumableJS) in turn has an event called fileProgress, that is called when the upload is progressing. If I do nothing during that event, the bar is not updating. If I put $scope.$apply() there, the bar is updated accordingly, but I get the digest and/or apply already in progress error. Finally, with the help of the $$phase check I get the best of both worlds, an updated progress bar without any errors.

那么在不干扰角度处理顺序的情况下更新我的条形图的正确替代方法是什么?

So what is the correct alternative to get my bar updated while not interfering with the angulars processing order?

推荐答案

在您的情况下,您正在尝试运行一个摘要周期,而摘要周期已经处于阶段.所以它抛出一个错误

In your case you are trying to run a digest cycle, when a digest cycle is already in phase. So it's throwing an error

你可以使用像 setTimeout(fn,0) 这样的东西.它的基本作用是立即将新消息添加到队列中,并在当前执行的代码完成时进行处理.

You can use something like setTimeout(fn,0). What it basically does is it adds new message to the queue immediately, and will be processed when the currently executing code is finished.

因此,在您明确执行 $scope.$apply() 的 angular 代码中,将其更改为下面的代码,它应该可以工作.

So in your angular code, where you are explicitly doing your $scope.$apply(), change it to the code below and it should work.

$timeout(function(){
   $scope.$apply();
},0)

这篇关于错误:$rootScope:inprog -- 在 angular 中“不"执行 $apply 的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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