简体   繁体   中英

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 ).

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. It doesn't work hiwever, because at the moment the click is triggered, the DOM element has not yet been created by Angular.

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 ". 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. Angular needs a chance to update the 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.

$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. Here's another question to get you started: How to register event while angularjs finish rendering UI

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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