在 $digest(引发 DOM 事件)之后推迟 angularjs 观察执行 [英] Defer angularjs watch execution after $digest (raising DOM event)

查看:25
本文介绍了在 $digest(引发 DOM 事件)之后推迟 angularjs 观察执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个触发 DOM 事件的手表:

I have a watch that triggers a DOM event:

scope.$watch(function() { return controller.selected; }, function(selected) {
    if (selected) {
        $input.trigger('focus');
    }
});

问题是我有一个处理 scope.$apply 的焦点"处理程序.

The issue is that I have a handler on 'focus' that does a scope.$apply.

$input.bind('focus', function() {
    scope.$apply(function() { controller.focused = true; });
});

因此,当我的 $watch$digest 内部被触发时,它会导致错误,因为它试图触发另一个 $digest.

So when my $watch is fired from inside a $digest it causes an error because it tries to trigger another $digest.

我的解决方法是将触发器放在 $timeout 中.

The workaround I have is to put the trigger in a $timeout.

scope.$watch(function() { return controller.selected; }, function(selected) {
    if (selected) {
        $timeout(function() { $input.trigger('focus'); });
    }
});

这有效......到目前为止.这是处理这个问题的正确方法吗?我不确定这是否适用于所有情况,我想看看是否有一种经过角度批准的方式来在摘要之后延迟一段代码.

This works ... so far. Is this the proper way to handle this? I'm not sure if this catches every case and would like to see if there is an angular approved way to have a piece of code defer for after the digest.

谢谢!

推荐答案

$timeout 通常用于在摘要循环之后(以及在浏览器呈现之后)运行某些内容.

$timeout is normally what is used to run something after a digest cycle (and after the browser renders).

$timeout 将导致在函数执行后执行另一个摘要循环.如果您的 trigger 不影响任何 Angular,您可以将 invokeApply 参数设置为 false 以避免运行另一个摘要循环.

$timeout will cause another digest cycle to be executed after the function is executed. If your trigger does not affect anything Angular, you can set the invokeApply argument to false to avoid running another digest cycle.

如果您希望回调在浏览器呈现之前运行:如果代码使用$evalAsync从指令排队,它应该运行在 DOM 被 Angular 操作之后,但在浏览器呈现之前.但是,如果代码使用 $evalAsync 从控制器排队,它将在 DOM 被 Angular 操作之前(并且在浏览器呈现之前)运行.另请参阅https://stackoverflow.com/a/17303759/215945.

If you want your callback to run before the browser renders: If code is queued using $evalAsync from a directive, it should run after the DOM has been manipulated by Angular, but before the browser renders. However, if code is queued using $evalAsync from a controller, it will run before the DOM has been manipulated by Angular (and before the browser renders). See also https://stackoverflow.com/a/17303759/215945.

这篇关于在 $digest(引发 DOM 事件)之后推迟 angularjs 观察执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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