【问题标题】:Adding jQuery plugin to angular app将 jQuery 插件添加到 Angular 应用程序
【发布时间】:2018-02-05 13:59:21
【问题描述】:

使用的框架

  1. 角度:5.2.3
  2. 基金会(Zurb):6.2.4

使用

创建了一个角度应用程序
> ng new foundation-plugin-app --style=sass
> cd foundation-plugin-app
> npm install foundation-sites --save

在此之前一切都按预期工作。
然后我加了foundation-datepicker

> npm install foundation-datepicker --save

这就是插件的初始化方式。

$('#scenario_start_date').fdatepicker({
  initialDate: '02-12-1989',
  format: 'mm-dd-yyyy',
  disableDblClickSelection: true,
  leftArrow: '<<',
  rightArrow: '>>',
  closeIcon: 'X',
  closeButton: true
});

现在,要使其正常工作,请按照以下步骤操作 1.在app.component.ts中添加styleUrls

styleUrls: [
    // ...,
    '../../node_modules/foundation-datepicker/scss/foundation-datepicker.scss'    ]

2.在angular-cli.json中添加scripts

"scripts": [
    "node_modules/foundation-datepicker/js/foundation-datepicker.js"
]

3.将typings添加到app.component.ts

npm install --save-dev @types/jquery

并将jqueryfoundation-datepicker 插件导入页面

import * as $ from 'jquery';
import 'foundation-datepicker';

4.最后,调用ngOnInit()中的插件app.component.ts

$('#scenario_start_date').fdatepicker(/*...*/);

这给出了错误

fdatepicker 未定义。 所以我将其类型转换为

(<any>$('#scenario_start_date')).fdatepicker(/*...*/);

抑制错误。

这给出了一个新的错误

未捕获的类型错误:无法读取未定义的属性“fn”

在 eval (webpack-internal:///../../../../foundation-datepicker/js/foundation-datepicker.min.js:1)
在 eval (webpack-internal:///../../../../foundation-datepicker/js/foundation-datepicker.min.js:1)
在对象.../../../../foundation-datepicker/js/foundation-datepicker.min.js (vendor.bundle.js:36)
在 __ webpack_require __ (inline.bundle.js:55)
在 eval (webpack-internal:///../../../../../src/app/app.component.ts:15)
在对象.../../../../../src/app/app.component.ts (main.bundle.js:21)
在 __ webpack_require __ (inline.bundle.js:55)
在 eval (webpack-internal:///../../../../../src/app/app.module.ts:11)
在对象.../../../../../src/app/app.module.ts (main.bundle.js:29)
在 __ webpack_require __ (inline.bundle.js:55)

我的代码做错了什么?任何指针都会有所帮助。

【问题讨论】:

  • 我认为您忘记将JQuery.js 包含到angular-cli.json
  • @abbas amiri:不。它被添加为依赖项。基金会需要它。当我 console.log 它时,$("#scenario_start_date") 也在工作。
  • 好吧,除了我添加了jquery,它对我有用。

标签: angular jquery-plugins zurb-foundation zurb-foundation-6


【解决方案1】:

您的导入语句似乎是错误的。

请尝试import $ from 'jquery';

并确保 jQuery 与您生成的捆绑文件捆绑在一起。

在您的情况下,它要么不是全局导出的,要么不包含在窗口上下文中。

在这种情况下尝试

window.jQuery = $;
window.$ = $;

【讨论】:

  • 为什么这不是一个答案? jQuery 在他的例子中是未定义的,因为他的导入是错误的。
  • 你的解决方案对我不起作用,但这个解决方案对我有用stackoverflow.com/a/50020329/89605
  • 这是 TypeScript 相关的,也是一个不同的问题 imo。
猜你喜欢
  • 2015-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多