jquery - 如何将Angular变量传递给jQuery函数
问题描述
我认为这应该相当简单,但对于我的生活,我无法让它发挥作用。
我有一个角字符串(占位符),我想从 $document.ready() 上触发的 jQuery 函数中引用它。基本上这就是我所拥有的:
placeholder: string;
ngOnInit() {
this.translateService.get(['']).subscribe(translations => {
this.placeholder = this.translateService.instant('placeholder');
console.log('PLACEHOLDER', this.placeholder); <<<<<<<<< has expected value
});
$(document).ready(function () {
console.log('READY', this.placeholder); <<<<<<<<< undefined
$('#dropDown').select2({
placeholder: this.placeholder,
data: [
...
]
});
});
}
如何从 jQuery 函数中引用 this.placeholder?
解决方案
当您使用function
关键字时,它会定义自己的this
,它会覆盖this
您认为使用的外部:
this.placeholder = 'Foo';
$(document).ready(function () {
console.log('READY', this.placeholder); // this is another this, local to the function
}
有两种解决方案:
用旧的 JS
在纯 JS 中,您可以移开外部this
以在内部使用它:
this.placeholder = 'Foo';
var that = this;
$(document).ready(function () {
console.log('READY', that.placeholder); // that refers to the outer this
}
使用现代 JS(ECMA 脚本 >5)
如果您可以使用 ECMA 脚本 >5 的现代浏览器,则可以使用箭头函数() => {}
代替function() {}
,它会自动保留外部 this:
this.placeholder = 'Foo';
$(document).ready(() => {
console.log('READY', this.placeholder); // () => {} does not override this
}
推荐阅读
- javascript - 这对于 JavaScript 绑定方法的 Polyfill 来说是一个可接受的解决方案吗?
- java - 从数组中获取重复项并将重复项复制到另一个数组中
- c# - Npgsql 异常:列 c.consrc 不存在
- python - fe_sendauth:Composer 中没有提供密码
- audio - 是否有用于语速的标记数据集?使用快速、中速、慢速或基于每分钟字数的标签?
- windows - 如何在 Windows 10 azure 虚拟机中使用 virtualbox
- azure-active-directory - Azure Active Directory 中为我的 Web API 配置的令牌生命周期
- xslt - 如何使用 2.0 版计算 XSLT 中数字的绝对值
- python - 如何解决 pandas 的内存分配问题?
- php - 无法在实时服务器上找到我的 php ini 文件?