【发布时间】:2017-11-05 00:02:26
【问题描述】:
我正在尝试将 typeahead.js 与 Angular 2 一起使用(以利用 Bloodhound 功能,因为它是目前最好的功能)。但是我在将 js 文件导入项目时遇到了困难。
我在 index.html 中有以下内容:
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
和预输入文件:
<script src="https://cdnjs.cloudflare.com/ajax/libs/typeahead.js/0.11.1/typeahead.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/corejs-typeahead/1.1.1/bloodhound.min.js"></script>
我还在 systemjs.config 中导入了 jQuery,如下所示:
..
map: {
'jquery': 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js',
}..
我在 ngAfterViewInit 方法中有 jQuery:
ngAfterViewInit() {
console.log("jQuery is ready");
// constructs the suggestion engine
var states = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.whitespace,
queryTokenizer: Bloodhound.tokenizers.whitespace,
// `states` is an array of state names defined in "The Basics"
local: states
});
$('#bloodhound .typeahead').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'states',
source: states
});
}
jQuery 工作正常(由控制台日志条目确认)。但是我收到以下错误:
jQuery.Deferred 异常:$(...).typeahead 不是函数 TypeError: $(...).typeahead 不是函数
和
ERROR TypeError: $(...).typeahead 不是函数
【问题讨论】:
-
尝试不使用 $(document).ready 并直接在 ngAfterViewInit 中代替? (会在文档准备好后触发,所以添加到 document.ready 事件中没有意义)
-
我已经删除了 document.ready 事件,但是我仍然收到相同的错误:错误错误:未捕获(承诺中):TypeError:$(...).typeahead 不是函数
-
这个 plunk 没有得到错误 - 它在 ngAfterViewInit 中有你的代码:plnkr.co/edit/Xvm0zwut4on8n6LNJVHL?p=preview 也在 index.html 中看到 - 你是否在 angular 脚本之前添加了你的 typeahead 脚本标签?
-
我已将 typeahead 更改为在 angular 脚本之前,但仍然出现相同的错误 ('typeahead': 'cdnjs.cloudflare.com/ajax/libs/typeahead.js/0.11.1/…) - 我确实导入了 2 个 jQuery 脚本 - 通过索引.html 和 system.config,这可能是问题所在?
-
是的,尝试从 system.config 中删除 jquery。在我向您展示的 plunk 中,它仅在 index.html 中作为脚本标记。
标签: javascript jquery angular2-forms typeahead.js twitter-typeahead