我认为这应该很简单,但是对于我的一生,我无法使其正常运行。
我有一个角度字符串(占位符),我想从$ 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?
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
在Angular中使用jQuery时,需要注意this
上下文的改变。在你的代码中,$(document).ready()
内的this
并不指向Angular组件实例,因此无法直接访问到this.placeholder
。为了解决这个问题,你可以使用箭头函数来保持正确的this
上下文,或者将组件实例赋值给一个变量并在jQuery函数内部使用这个变量。下面是两种解决方法:
ngOnInit() {
this.translateService.get(['']).subscribe(translations => {
this.placeholder = this.translateService.instant('placeholder');
console.log('PLACEHOLDER', this.placeholder);
$(document).ready(() => { // 使用箭头函数
console.log('READY', this.placeholder);
});
});
}
ngOnInit() {
const that = this; // 保存组件实例到that变量
this.translateService.get(['']).subscribe(translations => {
that.placeholder = that.translateService.instant('placeholder'); // 使用that而不是this
console.log('PLACEHOLDER', that.placeholder);
$(document).ready(function () {
console.log('READY', that.placeholder); // 同样使用that
});
});
}
在这两种方法中,第一种(箭头函数)是更现代且推荐的做法,因为它能更清晰地处理作用域问题,避免了常规函数绑定this
的需要。不过,请注意过度依赖jQuery与Angular的组合可能不是最佳实践,因为Angular自身提供了强大的数据绑定和DOM操作能力,大多数情况下可以直接使用Angular的方式来实现相同的功能。