访问jquery中的angular2变量

我在angular2项目中使用jQuery来做一些事情。 但我无法使用我在angular2中声明的变量来在jQuery中使用。 我有这样的事情:

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

这会给我一个错误,即参数未定义。 我想这是因为我用this 。 我还可以做些什么?

您需要使用箭头函数表达式() => {} )将其保留在范围内。 尝试:

 export class AddExerciseComponent implements OnInit { parameters:Array = ["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不会将您的回调视为在调用函数的范围内,从而使其无法用于从您认为自己所在的范围调用数据。通过使用箭头函数,范围已保存,可用于按预期访问数据。

如果你想在jquery中使用角度变量动画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"); } }); 

将此 (实例)的角度分配给Jquery的this (实例)以在JQuery中使用角度变量

 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); });