简体   繁体   English

如何知道DOM何时完成渲染

[英]How to know when the DOM has finished rendering

I'm trying to figure out how to know when the DOM is ready, after en element is automatically generated in by AngularJS (in an ng-repeat ). 在AngularJS(在ng-repeat )自动生成en元素之后,我试图找出如何知道DOM准备就绪的时间。

In my case, I create a new row in a table (which is an ng-repeat on an array) and I would like immediately to programmatically trigger a click event on an element inside a row. 就我而言,我在表中创建了新行(这是数组上的ng-repeat ),我想立即编程方式触发行内元素的click事件。 It doesn't work hiwever, because at the moment the click is triggered, the DOM element has not yet been created by Angular. 但是,它不起作用,因为在触发click的那一刻,Angular尚未创建DOM元素。

What I would like to have is something (an event) that could tell me " hey I've finished creating your DOM element, go on and do whatever you want with me ". 我想拥有的东西(一个事件)可以告诉我“ 嘿,我已经完成了创建DOM元素的操作,继续做我想做的一切 ”。 I searched for something like that but didn't really find anything who could do just that. 我搜索了类似的内容,但没有真正找到可以做到这一点的东西。

I created a plunkr illustrating the problem. 我创建了一个说明问题的插件

You're on the right track with the $timeout, but you don't need a long delay. 使用$ timeout可以使您走上正确的轨道,但是不需要很长的延迟。 Angular needs a chance to update the DOM. Angular需要一个机会来更新DOM。 By calling $timeout with no second parameter, you can basically say "Do this as soon as the current thread of work is done", so it'll run as soon as Angular is done modifying the DOM. 通过调用没有第二个参数的$ timeout,您基本上可以说“在当前工作线程完成后立即执行此操作”,因此它将在Angular修改DOM后立即运行。

$scope.add_row = function() {
  $scope.table_rows.push({text: 'blabla'});
  var row = '#row'+($scope.table_rows.length-1)+' input';
  $timeout(function() {
    $(row).click();
  });
}

EDIT : That being said, this is probably a place where a directive would be better. 编辑 :话虽这么说,这可能是一个指令会更好的地方。 Manipulating the DOM (even just firing click events) isn't something you're supposed to do in the controller. 操纵DOM(甚至只是触发单击事件)并不是您应该在控制器中执行的操作。 Here's another question to get you started: How to register event while angularjs finish rendering UI 这是另一个让您入门的问题: 如何在angularjs完成呈现UI的同时注册事件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM