简体   繁体   中英

How to access DOM element in AngularJS

I'm new to AngularJS. I have an app with basic routing etc but I'd like to add a script that will add some interactivity to my home screen. This is a typewriter js script:

const texts = ['123', '456', '789'];
let count = 0;
let index = 0;
let currentText = '';
let letter = '';

(function type() {
  if (count === texts.length) {
    count = 0;
  }
  currentText = texts[count];
  letter = currentText.slice(0, ++index);

  document.querySelector(".typing").innerHTML = letter;
  angular.element(document.querySelector('.typing'));

  if (letter.length === currentText.length) {
    count++;
    index = 0;
  }
  setTimeout(type, 400);
})();

This works locally but when I deploy to Heroku it says:

Uncaught TypeError: Cannot set property 'innerHTML' of null

This tells me that the script executes before the homepage view is loaded. What's the best solution for this. Can I stick this code inside app.js and if so, how do I do that?

I have already tried to wrap my code inside window.onload and it didn't make any difference.

Firstly, In angularjs scripts are wrapped inside a controller/service/factories which should be registered in your app module.

Check the below tutorial https://www.w3schools.com/angular/angular_controllers.asp

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