Angular 4 JS script not working after changing route

[亡魂溺海] 提交于 2021-02-20 04:42:45

问题


I try to load a script via angular-cli to sync two divs. When page is loaded for the first time, the script is working fine. Aftter that I change the route via Navigation. When going back to the first page, the script is not working anymore.

Angular CLI:

  "scripts": [
    ....
    "assets/scripts/scrollsync.js"
  ]

scrollsync.js:

$(function() {
  $('#column-item-container').on('scroll', function () {
    $('#row-lead-container').scrollTop($(this).scrollTop());
  });

  $('#column-item-container').on('scroll', function () {
    $('#column-lead-container').scrollLeft($(this).scrollLeft());
  });
});

I try to figure out if the script is still present to set a timeout with 1000ms sending some to console, that works fine. I looks like the binding is not working anymore. Some advice to fix this problem? Thank you!


回答1:


This issue probably happening because most of third party library or custom code initialize on document ready event. So that's why it work first time. Once you navigate to another page and come back on same page, angular not reloading page, it just render html part and document ready event not fire.

Solution

  • Bind event when your page open, not on document ready.
  • You can make a directive to bind scroll event, directive will always bind event when dom element bind, it not depend on document ready event.


来源:https://stackoverflow.com/questions/46348090/angular-4-js-script-not-working-after-changing-route

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!