angular - ng-if - 如何在渲染ng-if模板后回调 [英] angular - ng-if - how to callback after ng-if template has been rendered

查看:265
本文介绍了angular - ng-if - 如何在渲染ng-if模板后回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Angular中,我需要在加载了某个类的元素之后调用一个函数。
元素的显示通过ng-if ='expr'控制。 $ scope.expr的值在某个ajax调用响应后设置。



现在,如果我尝试将$ watch放在expr上,或者使用$ evalAsync。它不起作用。可能是因为这些事件是在模板部分实际运行之前运行的。



这是一个示例代码: http://jsbin.com/kuyas/1/edit
这里我需要一个关于ng的回调类型 - 如果在模板渲染后执行它。

解决方案

问题是没有办法知道是否使用摘要循环完成了角度,确保所有元素都已渲染。



要解决此问题,有两个选项


  1. 包装你的回调函数在指令中。在ng-if中包含该指令。并且只有当你想要执行回调时才使该表达式成为现实。

  2. 在里面调用你的回调函数, setTimeOut(function(){...},0 ); 因为默认情况下浏览器会将所有事件保存在队列中,因此,当摘要循环运行时,您的回调函数将进入队列并在摘要循环结束后立即执行。


in Angular, I need to call a function after an element with certain class has been loaded. Display of the element is controlled via ng-if='expr'. Value of $scope.expr is set after some ajax call has responded.

Now, if I try putting $watch on expr, or using $evalAsync. it is not working. probably the reason being that these events are run before the template part actually runs.

Here is a sample code : http://jsbin.com/kuyas/1/edit Here I need a callback sort of thing on ng-if that gets executed after the template has rendered.

解决方案

Problem was that there is no way to know if angular is done with the digest loop, ensuring that all elements have been rendered.

To solve this issue, there were two options

  1. Wrap your callback function in a directive. include that directive in ng-if. and make that expression true only when u want your callback to be executed.
  2. Call your callback function inside, setTimeOut(function(){ ... }, 0); as browsers by default keep all events in a queue, therefore, when digest loop is running, your callback function will enter the queue and get executed as soon digest loop is over.

这篇关于angular - ng-if - 如何在渲染ng-if模板后回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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