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

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

问题描述

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

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.

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

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.

这是一个示例代码:http://jsbin.com/kuyas/1/edit这里我需要一个关于 ng-if 的回调函数,它会在模板呈现后执行.

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.

推荐答案

问题是没有办法知道 angular 是否通过摘要循环完成,确保所有元素都已渲染.

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. 将您的回调函数包装在一个指令中.将该指令包含在 ng-if 中.并仅在您希望执行回调时才使该表达式为真.
  2. 在里面调用你的回调函数,setTimeOut(function(){ ... }, 0); 因为浏览器默认将所有事件保存在一个队列中,因此,当摘要循环运行时,你的回调函数将进入队列并在摘要循环结束后立即执行.
  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天全站免登陆