$ scope之后立即触发一个事件. [英] Fire an event immediately after $scope.$digest
问题描述
在我的AngularJS应用中,有几点要等待 $ scope
处理到DOM中,然后在其上运行一些代码,例如jQuery fadeIn
,例如.
In my AngularJS app, there's several points at which I want to wait for a $scope
to be processed into the DOM, and then run some code on it, like a jQuery fadeIn
, for example.
有没有办法听"digestComplete"消息?某种消息吗?
Is there a way to listen for a "digestComplete" message of some sort?
我当前的方法是:在设置了要渲染的任何 $ scope
变量后,立即使用0ms延迟的 setTimeout
,这样它将使示波器完成消化,然后运行代码,效果很好.唯一的问题是,在setTimeout返回之前,我偶尔会看到DOM渲染.我想要一种可以确保在摘要之后和渲染之前触发的方法.
My current method is: immediately after setting whatever $scope
variables I want rendered, use setTimeout
with a delay of 0 ms, so that it will let the scope finish digesting, and then run the code, which works perfectly. Only problem is, I very occasionally see the DOM render before that setTimeout returns. I'd like a method that is guaranteed to fire after digest, and before render.
推荐答案
在此 jQuery淡入--out-fiddle (我在 JSFiddles示例中找到了它) Wiki页面),作者定义了一个"fadey"指令,并在该指令的 link 函数中执行jQuery fadeIn(或fadeOut)"
In this jQuery fade-in-and-out fiddle (which I found it on the JSFiddles Examples wiki page), the author defines a "fadey" directive and performs the jQuery fadeIn (or fadeOut) in the directive's link function"
<li ng-repeat="item in items" fadey="500">
...
myApp.directive('fadey', function() {
return {
restrict: 'A',
link: function(scope, elm, attrs) {
var duration = parseInt(attrs.fadey);
if (isNaN(duration)) {
duration = 500;
}
elm = jQuery(elm); // this line is not needed if jQuery is loaded before Angular
elm.hide();
elm.fadeIn(duration)
另一种可能的解决方案是使用 $ evalAsync :请参阅Miško的此评论,其中指出:
Another possible solution is to use $evalAsync: see this comment by Miško, in which he states:
asyncEval在DOM构建之后但在浏览器呈现之前.我相信这是您想要附加jquery插件的时间.除此以外你会忽悠.如果您真的想在浏览器渲染后执行你可以做$ defer(fn,0);
The asyncEval is after the DOM construction but before the browser renders. I believe that is the time you want to attach the jquery plugins. otherwise you will have flicker. if you really want to do after the browser render you can do $defer(fn, 0);
($ defer重命名为$ timeout).
($defer was renamed $timeout).
但是,我认为使用指令(因为您正在操作DOM)是更好的方法.
However, I think using a directive (since you are manipulating the DOM) is the better approach.
这是 SO帖子,OP尝试收听用于作用域上的$ viewContentLoaded事件(这是另一种选择),以便应用一些jQuery函数.建议/答案再次是使用指令.
Here's a SO post where the OP tried listening for $viewContentLoaded events on the scope (which is yet another alternative), in order to apply some jQuery functions. The suggestion/answer was again to use a directive.
这篇关于$ scope之后立即触发一个事件.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!