簡體   English   中英

如何確保在渲染DOM之后調用我的dom操作函數/代碼?

[英]How to make sure my dom manipulating function/code is called after the DOM has been rendered?

我有一個角度應用程序,其中的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');
        }
      }
    }
  }
});

為此,您可以使用AnguarJS的$timeout服務。

因此,您必須將代碼包裝在回調中……

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

$timeoutwindow.setTimeout的AngularJS包裝器。 它在瀏覽器事件隊列中添加了一個新事件; 由於渲染引擎已經在此隊列中,因此瀏覽器將在處理隊列中的新任務之前完成頁面渲染。

我在我的博客上寫了一篇有關該主題的文章...當您需要在渲染DOM之后運行代碼時,可以將其用作參考。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM