【问题标题】:How to make sure my dom manipulating function/code is called after the DOM has been rendered?如何确保在渲染 DOM 后调用我的 dom 操作函数/代码?
【发布时间】:2013-04-16 11:51:25
【问题描述】:

我有一个 Angular 应用程序,其中 model 更改会触发一个弹出窗口,即 directive。我需要在此弹出窗口中选择一个元素,但 DOM 更新 ('$digest') 似乎是异步的,因此它在第一次显示/创建弹出窗口时不起作用。这适用于随后的弹出窗口。如何确保我的代码在创建弹出窗口并使用所有子元素呈现后运行?

这是等效的代码:

angular.module('mymodule', []).directive('myDirective', function() {
  return {
    require: ngModel,
    link: function($scope, element, attrs, ctrl) {
      element.addClass('foo');
      // And similar stuff
      ctrl.$render = function justRender() {
        if (ctrl.viewValue) {
          element.modal('show');
          /* Here I have code for selecting the contents of the pop-up,
             which doesn't work as DOM is not assuredly rendered at this time.
          */
        } else {
          element.modal('hide');
        }
      }
    }
  }
});

【问题讨论】:

  • 为什么你需要在这个弹出窗口中“选择”一个元素?选择后你想做什么?
  • @ganaraj:弹出窗口中显示了一些文本,我需要为用户显示预先选择的文本。

标签: javascript dom asynchronous angularjs angularjs-directive


【解决方案1】:

您可以为此使用 AnguarJS 的$timeout 服务。

所以你必须将你的代码包装在一个回调中......类似于:

$timeout(function() {
    // your code here
}, 0);

$timeoutwindow.setTimeout 的 AngularJS 包装器。 它在浏览器事件队列中添加一个新事件;由于渲染引擎已经在这个队列中,浏览器会在处理队列中的新任务之前完成页面渲染。

我在我的博客上写了一篇关于这个主题的文章......你可以在需要时将其作为参考run code after DOM has been rendered

【讨论】:

  • 谢谢,我不知道$timeout 在浏览器渲染之后运行。这行得通,但我很好奇如何将参数传递给回调?我找不到任何方法来做到这一点。
猜你喜欢
  • 1970-01-01
  • 2016-04-17
  • 1970-01-01
  • 1970-01-01
  • 2019-04-27
  • 2018-06-27
  • 2014-05-12
  • 2018-04-05
  • 2015-08-09
相关资源
最近更新 更多