首页 > 解决方案 > 如何将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?

标签: jqueryangular

解决方案


当您使用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
}

推荐阅读