0

我目前正在开发一个 Angular 4 项目,并且我正在使用 Angular cli。

目前我正在使用捆绑在一起的完美滚动条、bootstrap-slider.min.js、d3.js 等。

问题 当我们在 angular-cli 脚本数组中添加脚本文件时,它被捆绑在一起,并在浏览器中显示为script.bundle.js。

现在在script.js文件中,我们初始化了完美的滚动条,但是当页面加载时这根本不起作用。

我尝试了另一种方法是将代码放在文档就绪函数中,再次 ng 服务并刷新页面并且它工作。但是当更改路线并再次返回相同的视图时,它现在不起作用,我再次必须刷新它才能使其起作用。

我觉得一旦捆绑了脚本代码,它就无法正常工作,请问您有解决此问题的方法吗?

 "styles": [
    "../node_modules/bootstrap/dist/css/bootstrap.min.css",
    "../node_modules/perfect-scrollbar/dist/css/perfect-scrollbar.min.css",
    "styles.css"   ],   "scripts": [
    "../node_modules/jquery/dist/jquery.min.js",
    "../node_modules/bootstrap/dist/js/bootstrap.min.js",
    "../node_modules/perfect-scrollbar/dist/js/perfect-scrollbar.jquery.min.js",
    "../node_modules/d3/build/d3.min.js",
    "script.js"   ],

**Script.js**
/******* initializes custom scrollbars on elements *******/

  $(".perfect-scrollbar").each(function() {
      $(this).initCustomScrollbar();
  });

(function($) {

  $.fn.initCustomScrollbar = function() {

    $(this).perfectScrollbar();
  };
})(jQuery);

/******* initializes custom scrollbars on elements *******/
(function($) {

  $.fn.initCustomScrollbar = function() {

     $(this).perfectScrollbar();
      };
})(jQuery);
4

1 回答 1

0

您需要在ngAfterViewInit. 它不会像这样工作。

查看此链接,了解如何在 Angular 中使用第三方 js 而无需打字

Instead you should try and do all the modification AfterViewInit

npm install jquery --save and npm install bootstrap --save
Step two

Add the jquery scripts file in .angular-cli.json file

  "scripts": [
    "../node_modules/jquery/dist/jquery.js",
    "../node_modules/bootstrap-v4-dev/dist/js/bootstrap.min.js"
  ],
Step three

Adding a var in component to be used as a global variable

//using external js modules in Angular
declare var $: any;
Then in

ngAfterViewInit(){


        $(".perfect-scrollbar").each(function() {
          $(this).initCustomScrollbar();
      });

    (function($) {

      $.fn.initCustomScrollbar = function() {

        $(this).perfectScrollbar();
      };
    })(jQuery);

    /******* initializes custom scrollbars on elements *******/
    (function($) {

      $.fn.initCustomScrollbar = function() {

         $(this).perfectScrollbar();
          };
    })(jQuery);

}
于 2017-09-20T12:19:43.150 回答