Angular JS:$Scope.Apply() [英] Angular JS : $Scope.Apply()

查看:21
本文介绍了Angular JS:$Scope.Apply()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解更多关于 $scope.apply() 的实时使用情况.我们可以在控制器中使用 $scope.apply() 多少次?

I want to know more about $scope.apply() in real time usage. How many times can we use $scope.apply() in a controller?

例如,我有一些事件,如 ng-click() 、 ng-change() 、 ng-blur() 等.所有事件都在同一个控制器中.对于每个事件,我应该使用 $scope.apply() 吗?如果是,我收到错误:

For example, I have some events like ng-click() , ng-change(), ng-blur() etc. All events are in the same controller. For each and every event, should i use $scope.apply()? If yes, I am getting error :

Error: [$rootScope:inprog] [http://errors.angularjs.org/1.2.15/$rootScope/inprog?p0=%24apply][1]
at Error (native)

我在此论坛中读到,删除添加的 $scope.apply() 将解决该问题.

I have read in this forum that removing the addition $scope.apply() will resolve the issue.

angularjs $scope.$apply() 给出这个错误:错误: [$rootScope:inprog]

我实现了从代码中删除多个 $scope.apply() 的相同解决方案.错误消失了,但我想知道如何以及为什么?

I implemented the same solution of removing multiple $scope.apply() from the code. The errror is gone, but I want to know how and why?

谁能解释一下.

提前致谢.

推荐答案

$scope.apply() 是更新 DOM 的触发器,并且在大多数情况下(例如来自 DOM 的触发器)像 ng-click 触发器的评估被包裹在一个 $scope.apply() 中,因为它被传递到你的控制器.你通常不需要调用 $scope.apply() 因为它已经被处理了,但是如果你有一些没有正确更新的问题,你可以使用 $scope.apply() 基本上轻推它来更新.为了防止在已经评估 apply 时调用 apply,您可以像这样进行安全检查:

$scope.apply() is a trigger to update the DOM, and in most cases (such as a trigger from the DOM like ng-click the evaluation of the trigger is wrapped in a $scope.apply() as it is passed to your controller. You generally don't need to call $scope.apply() as it is already being handled, but if you are having issues with something not updating correctly, you can use $scope.apply() to basically nudge it to update. In order to prevent calling apply when apply is already being evaluated you can do a safe check like so:

if (!$scope.$$phase)
    $scope.apply();

$$phase 是一个 Angular 内部属性,当没有作用域应用正在进行时为空/未定义,当 $scope.apply() 有一个值> 正在执行.

The $$phase is an angular internal property that is null/undefined when no scope apply is in progress, and has a value when a $scope.apply() is executing.

$scope.apply() 的工作原理是找到最接近的子作用域(最里面的作用域)并检查更改、调用监视等,然后向上爬行直到到达根作用域范围,因此您可能会认为这是一个相当繁重的调用,应尽可能避免.

$scope.apply() works by finding the most child scope (the innermost scope) and checking for changes, calling watches, etc, then it crawls up the scopes until it gets to the root scope, so as you might imagine it is a rather heavy call and should be avoided when possible.

这篇关于Angular JS:$Scope.Apply()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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