访问jquery中的angular2变量

Access angular2 variables in jquery

本文关键字:变量 angular2 中的 jquery 访问      更新时间:2023-09-26

我在angular2项目中使用jQuery。但是我不能使用我在angular2中声明的变量在jQuery中使用。像这样:

export class AddExerciseComponent implements OnInit {
  parameters:Array<string> = ["FU"];
  constructor() { }
  ngOnInit() {

    $('.chips').on('chip.add', function(e, chip){
      this.parameters.push(chip.data);
      console.log(this.selectedValue);
    });
}

这将给我一个错误,参数没有定义。我想这是因为我用了this。我还能做什么?

您需要使用箭头函数表达式 (() => {})来保持this在范围内。试一试:

export class AddExerciseComponent implements OnInit {
parameters:Array<string> = ["FU"];
constructor() { }
ngOnInit() {
// removed function keyword and added () => {} syntax
  $('.chips').on('chip.add', (e, chip) => {  
    this.parameters.push(chip.data);
    console.log(this.selectedValue);
  });
}

当你作为一个常规的旧函数传递回调时,JavaScript不认为你的回调在调用函数的范围内,使this无法从你认为你所在的范围调用数据。通过使用Arrow函数,可以保存作用域,并且this可以用于访问预期的数据。

如果你想在jquery中使用angular变量animate ON-Complete函数回调,这就是你要做的:

$('#myDiv').animate({top: 70+"%"},{
  queue: false,
  duration: 1000,
  complete: () => {  
  //this is you angular variable of the class
      this.angularVar = 0;
      $("#myDiv").hide();
  //this is you angular variable of the class    
      this.showAnimation = false;
  //this is you angular class function
      this.angularFunction();
      console.log("animation complete");
  }
});

将angular的this(instance)赋值给Jquery的this(instance)以使用Jquery内部的angular变量

let jQueryInstance = this; // This line will assign all the angular instances to jQueryInstance variable.
$('.chips').on('chip.add', (e, chip) => { 
    /* this.parameters.push(chip.data); */
    // Instead of the above line we have to use like below
    jQueryInstance.parameters.push(chip.data); // instead of "this", "jQueryInstance" is used
    // console.log(this.selectedValue);
    console.log(jQueryInstance.selectedValue);
  });