1

Edit: Actually, this isn't a duplicate. I'm asking how to run code once the Dynamic DOM is available, not the Static DOM:

enter image description here

Because my textareas are inside an ngRepeat, so they aren't available in the Static DOM.


I'm using autosize in an Angular app. I'm trying to call autosize like this at the beginning of my controller:

autosize(document.getElementsByTagName('textarea'));

It doesn't work, presumably because at the time the function is called, document.getElementsByTagName is empty.

So I need to call the function after the DOM elements have been rendered. How can I do that?

Note: I also tried putting it in the run block, but that didn't work either.

Adam Zerner
  • 17,797
  • 15
  • 90
  • 156

1 Answers1

2

That's an instance of what is usually described as 'all DOM stuff goes to directives'. Integrating third-party code with Angular data binding will require some additional measures, but just for the initialization it's that easy:

app.directive('textarea', function ($timeout) {
  return {
    restrict: 'E',
    link: function (scope, element) {
      $timeout(function () {
        autosize(element[0]);
      });
    }
  };
});

$timeout with zero delay makes sure that the code runs after DOM has been rendered with initial state (this is the case for ng-repeat in particular).

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • So would declaring a `textarea` directive mess anything up with the angular's [built in](https://docs.angularjs.org/api/ng/directive/textarea) one? – Adam Zerner Sep 03 '15 at 21:08
  • The doc refer to the directives [common to all form tags](https://github.com/angular/angular.js/blob/v1.4.3/src/ng/directive/validators.js). There's no `textarea` directive, but even if there was one, it is perfectly safe to have several directives with the same name, as long as their scopes, controllers and templates don't interfere (the same applies to every bunch of directives on the same element). – Estus Flask Sep 03 '15 at 21:42